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-4588
|
Bug: [BUG] A duplicate field exists in authentication table
### Bug Description
A duplicate field exists in authentication table(`three_ds_server_trans_id`) which is never populated. But is read during authentication response creation. Which results in null being returned all the time.###
### Expected Behavior
Should fetch three_ds_server_trans_id from `threeds_server_transaction_id` in `authenticaiton`.
### Actual Behavior
three_ds_server_trans_id is fetched from `three_ds_server_trans_id` in `authenticaiton`.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs
index 8840d287e54..ce2f02d087f 100644
--- a/crates/diesel_models/src/authentication.rs
+++ b/crates/diesel_models/src/authentication.rs
@@ -38,7 +38,6 @@ pub struct Authentication {
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
- pub three_ds_server_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: String,
pub payment_id: Option<String>,
@@ -83,7 +82,6 @@ pub struct AuthenticationNew {
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
- pub three_dsserver_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: String,
pub payment_id: Option<String>,
@@ -160,7 +158,6 @@ pub struct AuthenticationUpdateInternal {
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
- pub three_dsserver_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
}
@@ -191,7 +188,6 @@ impl Default for AuthenticationUpdateInternal {
challenge_request: Default::default(),
acs_reference_number: Default::default(),
acs_trans_id: Default::default(),
- three_dsserver_trans_id: Default::default(),
acs_signed_content: Default::default(),
}
}
@@ -224,7 +220,6 @@ impl AuthenticationUpdateInternal {
challenge_request,
acs_reference_number,
acs_trans_id,
- three_dsserver_trans_id,
acs_signed_content,
} = self;
Authentication {
@@ -256,7 +251,6 @@ impl AuthenticationUpdateInternal {
challenge_request: challenge_request.or(source.challenge_request),
acs_reference_number: acs_reference_number.or(source.acs_reference_number),
acs_trans_id: acs_trans_id.or(source.acs_trans_id),
- three_ds_server_trans_id: three_dsserver_trans_id.or(source.three_ds_server_trans_id),
acs_signed_content: acs_signed_content.or(source.acs_signed_content),
..source
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 70a227a310a..e283be3f526 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -108,7 +108,6 @@ diesel::table! {
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
- three_dsserver_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs
index bece5459236..e29c8b10232 100644
--- a/crates/router/src/core/authentication/utils.rs
+++ b/crates/router/src/core/authentication/utils.rs
@@ -177,7 +177,6 @@ pub async fn create_new_authentication(
challenge_request: None,
acs_reference_number: None,
acs_trans_id: None,
- three_dsserver_trans_id: None,
acs_signed_content: None,
profile_id,
payment_id,
diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs
index 0f4aef679c5..398af72f8bd 100644
--- a/crates/router/src/db/authentication.rs
+++ b/crates/router/src/db/authentication.rs
@@ -143,7 +143,6 @@ impl AuthenticationInterface for MockDb {
challenge_request: authentication.challenge_request,
acs_reference_number: authentication.acs_reference_number,
acs_trans_id: authentication.acs_trans_id,
- three_ds_server_trans_id: authentication.three_dsserver_trans_id,
acs_signed_content: authentication.acs_signed_content,
profile_id: authentication.profile_id,
payment_id: authentication.payment_id,
diff --git a/crates/router/src/types/api/authentication.rs b/crates/router/src/types/api/authentication.rs
index 92bcd1ae73b..3e4a494f658 100644
--- a/crates/router/src/types/api/authentication.rs
+++ b/crates/router/src/types/api/authentication.rs
@@ -50,7 +50,7 @@ impl TryFrom<storage::Authentication> for AuthenticationResponse {
challenge_request: authentication.challenge_request,
acs_reference_number: authentication.acs_reference_number,
acs_trans_id: authentication.acs_trans_id,
- three_dsserver_trans_id: authentication.three_ds_server_trans_id,
+ three_dsserver_trans_id: authentication.threeds_server_transaction_id,
acs_signed_content: authentication.acs_signed_content,
})
}
diff --git a/migrations/2024-05-08-111348_delete_unused_column_from_authentication/down.sql b/migrations/2024-05-08-111348_delete_unused_column_from_authentication/down.sql
new file mode 100644
index 00000000000..8459dd79c5a
--- /dev/null
+++ b/migrations/2024-05-08-111348_delete_unused_column_from_authentication/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE authentication ADD COLUMN three_dsserver_trans_id VARCHAR;
\ No newline at end of file
diff --git a/migrations/2024-05-08-111348_delete_unused_column_from_authentication/up.sql b/migrations/2024-05-08-111348_delete_unused_column_from_authentication/up.sql
new file mode 100644
index 00000000000..fdbe2332b32
--- /dev/null
+++ b/migrations/2024-05-08-111348_delete_unused_column_from_authentication/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE authentication DROP COLUMN three_dsserver_trans_id;
\ No newline at end of file
|
2024-05-08T11:56:22Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
there are two fields in `authentication`(`three_ds_server_trans_id` and `threeds_server_transaction_id`) table that hold the same data. Removed `three_ds_server_trans_id` column which is not being populated at all.
This caused confusion and as a result we were returning `three_ds_server_trans_id`. Which resulted in null being returned in `AuthenticationResponse` all the time.
Fixed that as well.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] 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 it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Manual.
Create a merchant with netcetera authentication connector and checkout payment connector
1. create a payment with "request_external_three_ds_authentication": true,
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_yWDRHoFLgGtQRwkccTm9nMENIESjKEgkxratJOAjLRUHDFp71Mzhy0OJguhBk47h' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "123456789",
"country_code": "12"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "123456789",
"country_code": "12"
}
},
"request_external_three_ds_authentication": true,
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
2. Confirm the payment
```
curl --location 'http://localhost:8080/payments/pay_CbBAoF959T5yIiPzc9JY/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_d9f3d219499e4867b7677eeb98e9d3f4' \
--data '{
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "115.99.183.2"
},
"client_secret": "pay_CbBAoF959T5yIiPzc9JY_secret_9ymuISdrQEAm5Lwi1RzR",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4929251897047956",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
}
}'
```
3. Do auth call.
```
curl --location 'http://localhost:8080/payments/pay_SLvW65GMYypubOUH4aGK/3ds/authentication' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_d9f3d219499e4867b7677eeb98e9d3f4' \
--data '{
"client_secret": "pay_SLvW65GMYypubOUH4aGK_secret_ZPTWR1YANmOxEu6mdMUs",
"device_channel": "BRW",
"threeds_method_comp_ind": "N"
}'
```
Should get below response. (`three_dsserver_trans_id` will differ)
```
{
"trans_status": "Y",
"acs_url": null,
"challenge_request": null,
"acs_reference_number": null,
"acs_trans_id": null,
"three_dsserver_trans_id": "a3a75c67-4c3c-4335-ba31-60f9515dc532",
"acs_signed_content": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
339da8b0c9a1e388b65ff5d82a162e758c85ec6b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4579
|
Bug: fix: verify email in decision manger
Currently decision manager is giving verify email flow for users who are already verified but not for users who are not verified. This should be other way around.
|
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index d635ac064fe..5a0388c7f36 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -42,7 +42,7 @@ impl SPTFlow {
Self::TOTP => Ok(true),
// Main email APIs
Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
- Self::VerifyEmail => Ok(user.0.is_verified),
+ Self::VerifyEmail => Ok(!user.0.is_verified),
// Final Checks
Self::ForceSetPassword => user.is_password_rotate_required(state),
Self::MerchantSelect => user
|
2024-05-08T07:09:15Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Currently decision manager is giving verify email flow for users who are already verified but not for users who are not verified. This should be other way around, so condition is negated.
### 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 #4579.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
As of now, this is only testable in local env. I've removed TOTP from decision manager and directly went to verify email flow.
Previously verify email flow is coming for only verified users, after this change it is coming for only non-verified users.
```
curl --location 'http://localhost:8080/user/from_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
If the user didn't verify their email, then the `token_type` in the response should be `verify_email`.
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDYxNjE1YjAtZjI5Yi00NWIyLWJmNmItODczNTYyYWU1ODhlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJtYWdpY19saW5rIiwiZXhwIjoxNzE0ODExOTAwfQ.CDErXJ89a1o3ROyAKvm6TFW1drHDnlcqg43OoBQjY6A",
"token_type": "verify_email"
}
```
If the user is already verified, then the user should get other flow which is not `verify_email`.
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDYxNjE1YjAtZjI5Yi00NWIyLWJmNmItODczNTYyYWU1ODhlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJtYWdpY19saW5rIiwiZXhwIjoxNzE0ODExOTAwfQ.CDErXJ89a1o3ROyAKvm6TFW1drHDnlcqg43OoBQjY6A",
"token_type": "user_info"
}
```
## Checklist
<!-- Put an `x` in 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
|
625b53182e20b50fde5def338e122a43457da0f2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4586
|
Bug: [BUG] Fix card expiry for savecard flows in cypresss
### Bug Description
-Resolved an issue in the savecard flow where card expiry was incorrectly sourced from the confirmBody.json, resulting in failures. Now, only the payment_token is utilized, ensuring successful payment transactions.
### Expected Behavior
It should take from savecrad confirm body instead confirm body.json and it shouldnt expect the expiry year for this flows
### Actual Behavior
It took from expiry year from confirmbody and leads to failure
### Steps To Reproduce
Current main if you run the test save card flow will fail in cypress
### Context For The Bug
_No response_
### Environment
Sandbox
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
2024-05-08T10:40:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
-Resolved an issue in the savecard flow where card expiry was incorrectly sourced from the confirmBody.json, resulting in failures. Now, only the payment_token is utilized, ensuring successful payment transactions.
-This pull request includes refactoring of the card_pm details to accommodate the addition of banks and wallet flows.
### 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
To enhance test coverage for wallet and bank redirect flows.
## How did you test it?
Ran the test manually
<img width="762" alt="Screenshot 2024-05-08 at 3 56 21 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/3981f38d-0276-41c2-9b06-5d5db02f1dc5">
## 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
|
339da8b0c9a1e388b65ff5d82a162e758c85ec6b
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4602
|
Bug: Pass `required_billing_contact_fields` field in apple pay session call based on dynamic fields
This change is required as part of the one click checkout where in which we expect apple pay to collect the billing details from the customer and pass it in the confirm call with the `payment_data`.
In order for apple pay to collect the billing details from customer we need to pass``"requiredBillingContactFields": ["postalAddress"]`` in the `/session` call. Hence we need to have a validation in the backend that checks for the dynamic fields for a specific connector and pass the `required_billing_contact_fields` to sdk.
|
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 884e0fd82f8..37d17dcff17 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -396,13 +396,11 @@ pub struct UnresolvedResponseReason {
Clone,
Debug,
Eq,
- PartialEq,
serde::Deserialize,
serde::Serialize,
strum::Display,
strum::EnumString,
ToSchema,
- Hash,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
@@ -430,6 +428,89 @@ pub enum FieldType {
DropDown { options: Vec<String> },
}
+impl FieldType {
+ pub fn get_billing_variants() -> Vec<Self> {
+ vec![
+ Self::UserBillingName,
+ Self::UserAddressLine1,
+ Self::UserAddressLine2,
+ Self::UserAddressCity,
+ Self::UserAddressPincode,
+ Self::UserAddressState,
+ Self::UserAddressCountry { options: vec![] },
+ ]
+ }
+}
+
+/// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing
+impl PartialEq for FieldType {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::UserCardNumber, Self::UserCardNumber) => true,
+ (Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true,
+ (Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true,
+ (Self::UserCardCvc, Self::UserCardCvc) => true,
+ (Self::UserFullName, Self::UserFullName) => true,
+ (Self::UserEmailAddress, Self::UserEmailAddress) => true,
+ (Self::UserPhoneNumber, Self::UserPhoneNumber) => true,
+ (Self::UserCountryCode, Self::UserCountryCode) => true,
+ (
+ Self::UserCountry {
+ options: options_self,
+ },
+ Self::UserCountry {
+ options: options_other,
+ },
+ ) => options_self.eq(options_other),
+ (
+ Self::UserCurrency {
+ options: options_self,
+ },
+ Self::UserCurrency {
+ options: options_other,
+ },
+ ) => options_self.eq(options_other),
+ (Self::UserBillingName, Self::UserBillingName) => true,
+ (Self::UserAddressLine1, Self::UserAddressLine1) => true,
+ (Self::UserAddressLine2, Self::UserAddressLine2) => true,
+ (Self::UserAddressCity, Self::UserAddressCity) => true,
+ (Self::UserAddressPincode, Self::UserAddressPincode) => true,
+ (Self::UserAddressState, Self::UserAddressState) => true,
+ (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true,
+ (Self::UserBlikCode, Self::UserBlikCode) => true,
+ (Self::UserBank, Self::UserBank) => true,
+ (Self::Text, Self::Text) => true,
+ (
+ Self::DropDown {
+ options: options_self,
+ },
+ Self::DropDown {
+ options: options_other,
+ },
+ ) => options_self.eq(options_other),
+ _unused => false,
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn test_partialeq_for_field_type() {
+ let user_address_country_is_us = FieldType::UserAddressCountry {
+ options: vec!["US".to_string()],
+ };
+
+ let user_address_country_is_all = FieldType::UserAddressCountry {
+ options: vec!["ALL".to_string()],
+ };
+
+ assert!(user_address_country_is_us.eq(&user_address_country_is_all))
+ }
+}
+
#[derive(
Debug,
serde::Deserialize,
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 96136d69370..b7a58b3b5b6 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -537,7 +537,7 @@ impl From<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>> for SurchargePercen
}
}
/// Required fields info used while listing the payment_method_data
-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema, Hash)]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)]
pub struct RequiredFieldInfo {
/// Required field for a payment_method through a payment_method_type
pub required_field: String,
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index f1ce53580aa..ad5c02f6baa 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3867,6 +3867,24 @@ pub struct GpayAllowedMethodsParameters {
pub allowed_auth_methods: Vec<String>,
/// The list of allowed card networks (ex: AMEX,JCB etc)
pub allowed_card_networks: Vec<String>,
+ /// Is billing address required
+ pub billing_address_required: Option<bool>,
+ /// Billing address parameters
+ pub billing_address_parameters: Option<GpayBillingAddressParameters>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct GpayBillingAddressParameters {
+ /// Is billing phone number required
+ pub phone_number_required: bool,
+ /// Billing address format
+ pub format: GpayBillingAddressFormat,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub enum GpayBillingAddressFormat {
+ FULL,
+ MIN,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -4213,6 +4231,8 @@ pub struct ApplePayPaymentRequest {
/// The list of supported networks
pub supported_networks: Option<Vec<String>>,
pub merchant_identifier: Option<String>,
+ /// The required billing contact fields for connector
+ pub required_billing_contact_fields: Option<Vec<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)]
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index f89c2e5921b..01332c9d29e 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -291,6 +291,8 @@ impl DashboardRequestPayload {
"MASTERCARD".to_string(),
"VISA".to_string(),
],
+ billing_address_required: None,
+ billing_address_parameters: None,
};
let allowed_payment_methods = payments::GpayAllowedPaymentMethods {
payment_method_type: String::from("CARD"),
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 7abbc3b77e4..66e951af7b2 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -388,6 +388,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
+ api_models::payments::GpayBillingAddressParameters,
+ api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 0630fef2748..251a928c09e 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -538,6 +538,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(session_token_data.merchant_identifier),
+ required_billing_contact_fields: None,
}),
connector: "bluesnap".to_string(),
delayed_session_token: false,
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 0b3f4fb48ce..686858008b6 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -550,6 +550,7 @@ impl<F>
merchant_capabilities: None,
supported_networks: None,
merchant_identifier: None,
+ required_billing_contact_fields: None,
},
),
connector: "payme".to_string(),
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index 5a318e5e440..7f84e301916 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -1223,6 +1223,7 @@ pub fn get_apple_pay_session<F, T>(
),
total: apple_pay_init_result.total.into(),
merchant_identifier: None,
+ required_billing_contact_fields: None,
}),
connector: "trustpay".to_string(),
delayed_session_token: true,
@@ -1326,6 +1327,8 @@ impl From<GpayAllowedMethodsParameters> for api_models::payments::GpayAllowedMet
Self {
allowed_auth_methods: value.allowed_auth_methods,
allowed_card_networks: value.allowed_card_networks,
+ billing_address_required: None,
+ billing_address_parameters: None,
}
}
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 66e0f144807..c83c73f7624 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -11,9 +11,13 @@ use crate::{
payments::{self, access_token, helpers, transformers, PaymentData},
},
headers, logger,
- routes::{self, metrics},
+ routes::{self, app::settings, metrics},
services,
- types::{self, api, domain},
+ types::{
+ self,
+ api::{self, enums},
+ domain,
+ },
utils::OptionExt,
};
@@ -78,6 +82,39 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
}
}
+/// This function checks if for a given connector, payment_method and payment_method_type,
+/// the list of required_field_type is present in dynamic fields
+fn is_dynamic_fields_required(
+ required_fields: &settings::RequiredFields,
+ payment_method: enums::PaymentMethod,
+ payment_method_type: enums::PaymentMethodType,
+ connector: &types::Connector,
+ required_field_type: Vec<enums::FieldType>,
+) -> bool {
+ required_fields
+ .0
+ .get(&payment_method)
+ .and_then(|pm_type| pm_type.0.get(&payment_method_type))
+ .and_then(|required_fields_for_connector| {
+ required_fields_for_connector.fields.get(connector)
+ })
+ .map(|required_fields_final| {
+ required_fields_final
+ .non_mandate
+ .iter()
+ .any(|(_, val)| required_field_type.contains(&val.field_type))
+ || required_fields_final
+ .mandate
+ .iter()
+ .any(|(_, val)| required_field_type.contains(&val.field_type))
+ || required_fields_final
+ .common
+ .iter()
+ .any(|(_, val)| required_field_type.contains(&val.field_type))
+ })
+ .unwrap_or(false)
+}
+
fn get_applepay_metadata(
connector_metadata: Option<common_utils::pii::SecretSerdeValue>,
) -> RouterResult<payment_types::ApplepaySessionTokenMetadata> {
@@ -247,6 +284,20 @@ async fn create_applepay_session_token(
router_data.request.to_owned(),
)?;
+ let billing_variants = enums::FieldType::get_billing_variants();
+
+ let required_billing_contact_fields = if is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::ApplePay,
+ &connector.connector_name,
+ billing_variants,
+ ) {
+ Some(vec!["postalAddress".to_string()])
+ } else {
+ None
+ };
+
// Get apple pay payment request
let applepay_payment_request = get_apple_pay_payment_request(
amount_info,
@@ -254,6 +305,7 @@ async fn create_applepay_session_token(
router_data.request.to_owned(),
apple_pay_session_request.merchant_identifier.as_str(),
merchant_business_country,
+ required_billing_contact_fields,
)?;
let applepay_session_request = build_apple_pay_session_request(
@@ -354,6 +406,7 @@ fn get_apple_pay_payment_request(
session_data: types::PaymentsSessionData,
merchant_identifier: &str,
merchant_business_country: Option<api_models::enums::CountryAlpha2>,
+ required_billing_contact_fields: Option<Vec<String>>,
) -> RouterResult<payment_types::ApplePayPaymentRequest> {
let applepay_payment_request = payment_types::ApplePayPaymentRequest {
country_code: merchant_business_country.or(session_data.country).ok_or(
@@ -366,6 +419,7 @@ fn get_apple_pay_payment_request(
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(merchant_identifier.to_string()),
+ required_billing_contact_fields,
};
Ok(applepay_payment_request)
}
@@ -443,6 +497,38 @@ fn create_gpay_session_token(
expected_format: "gpay_metadata_format".to_string(),
})?;
+ let billing_variants = enums::FieldType::get_billing_variants();
+
+ let is_billing_details_required = is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::GooglePay,
+ &connector.connector_name,
+ billing_variants,
+ );
+
+ let billing_address_parameters =
+ is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters {
+ phone_number_required: is_billing_details_required,
+ format: payment_types::GpayBillingAddressFormat::FULL,
+ });
+
+ let gpay_allowed_payment_methods = gpay_data
+ .data
+ .allowed_payment_methods
+ .into_iter()
+ .map(
+ |allowed_payment_methods| payment_types::GpayAllowedPaymentMethods {
+ parameters: payment_types::GpayAllowedMethodsParameters {
+ billing_address_required: Some(is_billing_details_required),
+ billing_address_parameters: billing_address_parameters.clone(),
+ ..allowed_payment_methods.parameters
+ },
+ ..allowed_payment_methods
+ },
+ )
+ .collect();
+
let session_data = router_data.request.clone();
let transaction_info = payment_types::GpayTransactionInfo {
country_code: session_data.country.unwrap_or_default(),
@@ -466,7 +552,7 @@ fn create_gpay_session_token(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: gpay_data.data.merchant_info,
- allowed_payment_methods: gpay_data.data.allowed_payment_methods,
+ allowed_payment_methods: gpay_allowed_payment_methods,
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 259d1669523..63f102268c1 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4982,6 +4982,14 @@
"merchant_identifier": {
"type": "string",
"nullable": true
+ },
+ "required_billing_contact_fields": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "The required billing contact fields for connector",
+ "nullable": true
}
}
},
@@ -9420,6 +9428,19 @@
"type": "string"
},
"description": "The list of allowed card networks (ex: AMEX,JCB etc)"
+ },
+ "billing_address_required": {
+ "type": "boolean",
+ "description": "Is billing address required",
+ "nullable": true
+ },
+ "billing_address_parameters": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/GpayBillingAddressParameters"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -9443,6 +9464,29 @@
}
}
},
+ "GpayBillingAddressFormat": {
+ "type": "string",
+ "enum": [
+ "FULL",
+ "MIN"
+ ]
+ },
+ "GpayBillingAddressParameters": {
+ "type": "object",
+ "required": [
+ "phone_number_required",
+ "format"
+ ],
+ "properties": {
+ "phone_number_required": {
+ "type": "boolean",
+ "description": "Is billing phone number required"
+ },
+ "format": {
+ "$ref": "#/components/schemas/GpayBillingAddressFormat"
+ }
+ }
+ },
"GpayMerchantInfo": {
"type": "object",
"required": [
|
2024-05-09T07:48:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This change is required as part of the one click checkout where in which we expect apple pay to collect the billing details from the customer and pass it in the confirm call with the `payment_data`.
In order for apple pay to collect the billing details from customer we need to pass``"requiredBillingContactFields": ["postalAddress"]`` in the `/session` call. Hence we need to have a validation in the backend that checks for the dynamic fields for a specific connector and pass the `required_billing_contact_fields` to sdk.
### 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 MCA for stripe
-> Apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}
```
-> Since no dynamic fields was not added for stripe the `required_billing_contact_fields` is `null`
<img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e4708058-ca0f-4d9c-8cc9-032097d9a5f1">
-> Create MCA create for cybersource
-> Apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}
```
<img width="1109" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/36aec432-6c2b-4bcf-a9ed-d5849fe96b19">
-> Session call having the `required_billing_contact_fields` being passed as the dynamic fields are present
<img width="1140" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e9d7a960-7d79-42a7-bbb6-4776cadc8fd5">
## Checklist
<!-- Put an `x` in 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
|
2a302eb5973c64d8b77f8110fdbeb536ccbe1488
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4567
|
Bug: Store `card_cvc` in extended_card_info and extend max ttl
Currently, the extended_card_info payload that is sent to merchant does not contain cvc. Include cvc too in the payload and extend the max ttl for the feature to be 2 hrs (7200 seconds)
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 75bd2a31d8e..13ad6b282e6 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1113,7 +1113,7 @@ pub struct ExtendedCardInfoConfig {
#[schema(value_type = String)]
pub public_key: Secret<String>,
/// TTL for extended card info
- #[schema(default = 900, maximum = 3600, value_type = u16)]
+ #[schema(default = 900, maximum = 7200, value_type = u16)]
#[serde(default)]
pub ttl_in_secs: TtlForExtendedCardInfo,
}
@@ -1137,7 +1137,7 @@ impl<'de> Deserialize<'de> for TtlForExtendedCardInfo {
// Check if value exceeds the maximum allowed
if value > consts::MAX_TTL_FOR_EXTENDED_CARD_INFO {
Err(serde::de::Error::custom(
- "ttl_in_secs must be less than or equal to 3600 (1hr)",
+ "ttl_in_secs must be less than or equal to 7200 (2hrs)",
))
} else {
Ok(Self(value))
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 8270ddaf3fe..213330b8e8d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -934,6 +934,10 @@ pub struct ExtendedCardInfo {
#[schema(value_type = String, example = "John Test")]
pub card_holder_name: Option<Secret<String>>,
+ /// The CVC number for the card
+ #[schema(value_type = String, example = "242")]
+ pub card_cvc: Secret<String>,
+
/// The name of the issuer of card
#[schema(example = "chase")]
pub card_issuer: Option<String>,
@@ -959,6 +963,7 @@ impl From<Card> for ExtendedCardInfo {
card_exp_month: value.card_exp_month,
card_exp_year: value.card_exp_year,
card_holder_name: value.card_holder_name,
+ card_cvc: value.card_cvc,
card_issuer: value.card_issuer,
card_network: value.card_network,
card_type: value.card_type,
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 509056152eb..94b53766db0 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -82,4 +82,4 @@ pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false;
pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60;
/// Max ttl for Extended card info in redis (in seconds)
-pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60;
+pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index c45a4aaaa10..ec7d820a139 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -8717,7 +8717,8 @@
"card_number",
"card_exp_month",
"card_exp_year",
- "card_holder_name"
+ "card_holder_name",
+ "card_cvc"
],
"properties": {
"card_number": {
@@ -8740,6 +8741,11 @@
"description": "The card holder's name",
"example": "John Test"
},
+ "card_cvc": {
+ "type": "string",
+ "description": "The CVC number for the card",
+ "example": "242"
+ },
"card_issuer": {
"type": "string",
"description": "The name of the issuer of card",
@@ -8786,7 +8792,7 @@
"format": "int32",
"description": "TTL for extended card info",
"default": 900,
- "maximum": 3600,
+ "maximum": 7200,
"minimum": 0
}
}
|
2024-05-07T10:37:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR includes `card_cvc` field too to be sent to merchant as part of extended card info. Also extends the maximum ttl for the feature from 1hr to 2hr.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. When tried to configure ttl more than 2 hrs

2. Extended card info decrypted after storing cvc

## Checklist
<!-- Put an `x` in 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
|
99bbc3982fa30f6ffd43334b1fa5da963975fe93
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4561
|
Bug: Setup Hyperswitch Web & Control center
# Context
Developer experience is one of the key tenets at Hyperswitch. Setting up and running Hyperswitch should be fun, fast and easy for all developers out there !!
However, when we fully open sourced Hyperswitch in Nov 2023, we had to create three repositories to easily manage Hyperswitch product suite from a compliance and from a developer productivity perspective. We feel that there is a lot of scope for optimixing the local setup of a multi-repository product suite like Hyperswitch.
# Problem Statement
As of now, our Docker Compose setup within the [juspay/hyperswitch](https://github.com/juspay/hyperswitch) repository only covers the backend services of the Hyperswitch apps server. The current setup lacks inclusion of the web client and the control center. Docker Compose setup needs to be extended to include these components seamlessly.
You can find the documentation for setting up the Hyperswitch app server (and other services including database, Redis, monitoring services) [here](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#run-hyperswitch-using-docker-compose), and the Docker Compose file [here](https://github.com/juspay/hyperswitch/blob/main/docker-compose.yml)
# How to Get Started
## Web Client Setup
- The [web client](https://github.com/juspay/hyperswitch-web) and React demo app don't have a Docker-based setup yet.
- Start by creating a Docker-based setup for the web client. Utilize a node-based Docker image to run the SDK and demo app
## Control Center
- The control center setup is simple, you can just include another service in the Docker Compose file to pull the control center image from Docker Hub
- Please Note: The control center however requires you to run the web client beforehand, and the web client URL must be configured in the control center configuration to be able to run it
## Integration
- Once Docker setups for both the web client and control center are available, integrate them into the existing Docker Compose setup.
- Ensure that the control center configuration references the web client URL correctly, and that the web client and React demo app configuration references the app server URL correctly.
# Expected outcome
Submit a pull request to the [juspay/hyperswitch](https://github.com/juspay/hyperswitch) repository with the following changes:
- Modify the Docker Compose file to include three new services: the web client, the React demo app (for the web client), and the control center.
- The pull request should enable anyone trying out Hyperswitch to set up all three components seamlessly, enhancing client adoption.
### Brownie points
- Providing clear and comprehensive technical documentation along with the Docker setup
Addressing these blockers will not only streamline the Docker Compose setup process but also enhance the overall user experience for developers integrating Hyperswitch. It is crucial for ensuring smooth adoption of Hyperswitch
_Originally posted by @NarsGNA in https://github.com/juspay/hyperswitch/discussions/4110_
|
diff --git a/docker-compose.yml b/docker-compose.yml
index e55008f1e34..32a7a6ef2f8 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -122,6 +122,39 @@ services:
labels:
logs: "promtail"
+### Web Client
+ hyperswitch-web:
+ ports:
+ - "9050:9050"
+ - "9060:9060"
+ - "5252:5252"
+ build:
+ context: ./docker
+ dockerfile: web.Dockerfile
+ environment:
+ - HYPERSWITCH_PUBLISHABLE_KEY=$HYPERSWITCH_PUBLISHABLE_KEY
+ - HYPERSWITCH_SECRET_KEY=$HYPERSWITCH_SECRET_KEY
+ - HYPERSWITCH_SERVER_URL=${HYPERSWITCH_SERVER_URL:-http://hyperswitch-server:8080}
+ - HYPERSWITCH_CLIENT_URL=${HYPERSWITCH_CLIENT_URL:-http://localhost:9050}
+ - SELF_SERVER_URL=${SELF_SERVER_URL:-http://localhost:5252}
+ - SDK_ENV=${SDK_ENV:-local}
+ - ENV_SDK_URL=${ENV_SDK_URL:-http://localhost:9050}
+ - ENV_BACKEND_URL=${ENV_BACKEND_URL:-http://localhost:8080}
+ - ENV_LOGGING_URL=${ENV_LOGGING_URL:-http://localhost:3100}
+ labels:
+ logs: "promtail"
+
+ ### Control Center
+ hyperswitch-control-center:
+ image: juspaydotin/hyperswitch-control-center:latest
+ ports:
+ - "9000:9000"
+ environment:
+ - apiBaseUrl=http://localhost:8080
+ - sdkBaseUrl=http://localhost:9050/HyperLoader.js
+ labels:
+ logs: "promtail"
+
### Clustered Redis setup
redis-cluster:
image: redis:7
diff --git a/docker/web.Dockerfile b/docker/web.Dockerfile
new file mode 100644
index 00000000000..532ce28fb7c
--- /dev/null
+++ b/docker/web.Dockerfile
@@ -0,0 +1,15 @@
+FROM node:lts
+
+RUN npm install concurrently -g
+
+WORKDIR /hyperswitch-web
+
+RUN git clone https://github.com/juspay/hyperswitch-web --depth 1 .
+
+RUN npm install
+
+EXPOSE 9050
+EXPOSE 5252
+EXPOSE 9060
+
+CMD concurrently "npm run re:build && npm run start" "npm run start:playground"
\ No newline at end of file
|
2024-03-26T08:35: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 web client and control center services to docker-compose.yml
REF : #4110
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
|
b0133f33693575f2145d295eff78dd07b61efcda
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4566
|
Bug: Fix deserialization errors for sdk_eligible_payment_methods
### Feature Description
fix deserialization errors for sdk_eligible_payment_methods
### Possible Implementation
A small fix
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index b5585a84b32..f0dad483c65 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -615,4 +615,4 @@ refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
[saved_payment_methods]
-sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
+sdk_eligible_payment_methods = "card"
\ No newline at end of file
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index fe47b10b543..faf3bb7f466 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -321,4 +321,4 @@ connectors_with_webhook_source_verification_call = "paypal" # List of co
keys = "user-agent"
[saved_payment_methods]
-sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
+sdk_eligible_payment_methods = "card"
\ No newline at end of file
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 3135b3d5682..f564b976bc0 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -332,4 +332,4 @@ connectors_with_webhook_source_verification_call = "paypal" # List of connec
keys = "user-agent"
[saved_payment_methods]
-sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
+sdk_eligible_payment_methods = "card"
\ No newline at end of file
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 921301ebd6f..35c8a2ba3d6 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -336,4 +336,4 @@ connectors_with_webhook_source_verification_call = "paypal" # List of con
keys = "user-agent"
[saved_payment_methods]
-sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
+sdk_eligible_payment_methods = "card"
\ No newline at end of file
diff --git a/config/development.toml b/config/development.toml
index db7f1ed93f4..3f05872bc6a 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -617,4 +617,4 @@ refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
[saved_payment_methods]
-sdk_eligible_payment_methods = ["card"]
+sdk_eligible_payment_methods = "card"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 702d134f2d5..9fd22f46707 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -476,4 +476,4 @@ refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
[saved_payment_methods]
-sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
+sdk_eligible_payment_methods = "card"
\ No newline at end of file
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 12ce9c39d6f..adc09fb55af 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -167,7 +167,9 @@ pub struct PaymentMethodAuth {
}
#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
pub struct EligiblePaymentMethods {
+ #[serde(deserialize_with = "deserialize_hashset")]
pub sdk_eligible_payment_methods: HashSet<String>,
}
|
2024-05-07T05:01:17Z
|
## 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 -->
Fix for deployment
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
76b76eccc6e8e6b9f095c55430a024e1b576bde5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4572
|
Bug: Refactoring card fields in default.rs
add missing card default data fields in default.rs
|
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 3d4d56b45c5..4fcdd76992e 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -626,6 +626,53 @@ impl Default for super::settings::RequiredFields {
common: HashMap::new(),
}
),
+ (
+ enums::Connector::Billwerk,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
(
enums::Connector::Bluesnap,
RequiredFieldFinal {
@@ -700,6 +747,100 @@ impl Default for super::settings::RequiredFields {
common: HashMap::new(),
}
),
+ (
+ enums::Connector::Boku,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Braintree,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
(
enums::Connector::Checkout,
RequiredFieldFinal {
@@ -968,11 +1109,13 @@ impl Default for super::settings::RequiredFields {
common:HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Fiserv,
+ enums::Connector::DummyConnector1,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1012,14 +1155,15 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Forte,
+ enums::Connector::DummyConnector2,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1056,80 +1200,18 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
- (
- "billing.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
+ )
]
),
- common:HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Globalpay,
+ enums::Connector::DummyConnector3,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
- common: HashMap::from([
- (
- "payment_method_data.card.card_number".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_number".to_string(),
- display_name: "card_number".to_string(),
- field_type: enums::FieldType::UserCardNumber,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_exp_month".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_exp_month".to_string(),
- display_name: "card_exp_month".to_string(),
- field_type: enums::FieldType::UserCardExpiryMonth,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_exp_year".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_exp_year".to_string(),
- display_name: "card_exp_year".to_string(),
- field_type: enums::FieldType::UserCardExpiryYear,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_cvc".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_cvc".to_string(),
- display_name: "card_cvc".to_string(),
- field_type: enums::FieldType::UserCardCvc,
- value: None,
- }
- )
- ]),
- }
- ),
- (
- enums::Connector::Helcim,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1166,61 +1248,66 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
+ )
+ ]
+ ),
+ }
+ ),
+ #[cfg(feature = "dummy_connector")]
+ (
+ enums::Connector::DummyConnector4,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
(
- "billing.address.first_name".to_string(),
+ "payment_method_data.card.card_number".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
value: None,
}
),
(
- "billing.address.last_name".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "billing.address.zip".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserAddressPincode,
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
),
(
- "billing.address.line1".to_string(),
+ "payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserAddressLine1,
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
+ )
]
),
- common: HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Iatapay,
+ enums::Connector::DummyConnector5,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
- common: HashMap::new(),
- }
- ),
- (
- enums::Connector::Mollie,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1257,35 +1344,17 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
- (
- "billing.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
+ )
]
),
- common: HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Multisafepay,
+ enums::Connector::DummyConnector6,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate:HashMap::new(),
+ non_mandate: HashMap::new(),
common: HashMap::from(
[
(
@@ -1323,71 +1392,52 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
- (
- "billing.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.line1".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserAddressLine1,
- value: None,
- }
- ),
+ )
+ ]
+ ),
+ }
+ ),
+ #[cfg(feature = "dummy_connector")]
+ (
+ enums::Connector::DummyConnector7,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
(
- "billing.address.line2".to_string(),
+ "payment_method_data.card.card_number".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line2".to_string(),
- display_name: "line2".to_string(),
- field_type: enums::FieldType::UserAddressLine2,
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
value: None,
}
),
(
- "billing.address.city".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserAddressCity,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "billing.address.zip".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserAddressPincode,
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
),
(
- "billing.address.country".to_string(),
+ "payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
value: None,
}
)
@@ -1396,11 +1446,10 @@ impl Default for super::settings::RequiredFields {
}
),
(
- enums::Connector::Nexinets,
+ enums::Connector::Fiserv,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::new(),
- common: HashMap::from(
+ non_mandate: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1440,10 +1489,11 @@ impl Default for super::settings::RequiredFields {
)
]
),
+ common: HashMap::new(),
}
),
(
- enums::Connector::Nmi,
+ enums::Connector::Forte,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::from(
@@ -1488,7 +1538,7 @@ impl Default for super::settings::RequiredFields {
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
@@ -1497,31 +1547,66 @@ impl Default for super::settings::RequiredFields {
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
),
- (
- "billing.address.zip".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.zip".to_string(),
- display_name: "billing_zip".to_string(),
- field_type: enums::FieldType::UserAddressPincode,
- value: None,
- }
- ),
]
),
- common: HashMap::new(),
+ common:HashMap::new(),
}
),
(
- enums::Connector::Noon,
+ enums::Connector::Globalpay,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
- common: HashMap::from(
+ common: HashMap::from([
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]),
+ }
+ ),
+ (
+ enums::Connector::Helcim,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1563,7 +1648,7 @@ impl Default for super::settings::RequiredFields {
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
@@ -1572,21 +1657,47 @@ impl Default for super::settings::RequiredFields {
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
]
),
+ common: HashMap::new(),
}
),
(
- enums::Connector::Payme,
+ enums::Connector::Iatapay,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
- common: HashMap::from(
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Mollie,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1624,20 +1735,11 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
- (
- "email".to_string(),
- RequiredFieldInfo {
- required_field: "email".to_string(),
- display_name: "email".to_string(),
- field_type: enums::FieldType::UserEmailAddress,
- value: None,
- }
- ),
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
@@ -1653,13 +1755,15 @@ impl Default for super::settings::RequiredFields {
),
]
),
+ common: HashMap::new(),
}
),
(
- enums::Connector::Paypal,
+ enums::Connector::Multisafepay,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate:HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1696,25 +1800,92 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- )
- ]
- ),
- common: HashMap::new(),
- }
- ),
- (
- enums::Connector::Payu,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::from(
- [
+ ),
(
- "payment_method_data.card.card_number".to_string(),
+ "billing.address.first_name".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.card.card_number".to_string(),
- display_name: "card_number".to_string(),
- field_type: enums::FieldType::UserCardNumber,
- value: None,
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line2".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line2".to_string(),
+ display_name: "line2".to_string(),
+ field_type: enums::FieldType::UserAddressLine2,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Nexinets,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
}
),
(
@@ -1746,11 +1917,10 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
(
- enums::Connector::Powertranz,
+ enums::Connector::Nmi,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::from(
@@ -1795,7 +1965,7 @@ impl Default for super::settings::RequiredFields {
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
@@ -1804,21 +1974,31 @@ impl Default for super::settings::RequiredFields {
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.zip".to_string(),
+ display_name: "billing_zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
]
),
common: HashMap::new(),
}
),
(
- enums::Connector::Rapyd,
+ enums::Connector::Noon,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1876,14 +2056,14 @@ impl Default for super::settings::RequiredFields {
),
]
),
- common: HashMap::new(),
}
),
(
- enums::Connector::Shift4,
+ enums::Connector::Nuvei,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1923,13 +2103,14 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
- ),(
- enums::Connector::Stax,
+ ),
+ (
+ enums::Connector::Payme,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -1967,11 +2148,20 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
@@ -1987,15 +2177,60 @@ impl Default for super::settings::RequiredFields {
),
]
),
+ }
+ ),
+ (
+ enums::Connector::Paypal,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
common: HashMap::new(),
}
),
(
- enums::Connector::Stripe,
+ enums::Connector::Payu,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::new(),
- common:HashMap::from(
+ non_mandate: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2035,10 +2270,11 @@ impl Default for super::settings::RequiredFields {
)
]
),
+ common: HashMap::new(),
}
),
(
- enums::Connector::Trustpay,
+ enums::Connector::Powertranz,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::from(
@@ -2097,53 +2333,78 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ ]
+ ),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Rapyd,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
(
- "billing.address.line1".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserAddressLine1,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "billing.address.city".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserAddressCity,
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
),
(
- "billing.address.zip".to_string(),
+ "payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserAddressPincode,
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
value: None,
}
),
(
- "billing.address.country".to_string(),
+ "billing.address.first_name".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
value: None,
}
),
]
),
- common: HashMap::new()
+ common: HashMap::new(),
}
),
(
- enums::Connector::Tsys,
+ enums::Connector::Shift4,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::from(
@@ -2186,16 +2447,385 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common: HashMap::new()
+ common: HashMap::new(),
}
),
(
- enums::Connector::Worldline,
+ enums::Connector::Square,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from([
- (
- "payment_method_data.card.card_number".to_string(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Stax,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Stripe,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common:HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Trustpay,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ ]
+ ),
+ common: HashMap::new()
+ }
+ ),
+ (
+ enums::Connector::Tsys,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ common: HashMap::new()
+ }
+ ),
+ (
+ enums::Connector::Worldline,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from([
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ )
+ ]),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Worldpay,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from([
+ (
+ "payment_method_data.card.card_number".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.card.card_number".to_string(),
display_name: "card_number".to_string(),
@@ -2220,123 +2850,459 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
+ )
+ ]),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Zen,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from([
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
),
(
- "payment_method_data.card.card_cvc".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.card.card_cvc".to_string(),
- display_name: "card_cvc".to_string(),
- field_type: enums::FieldType::UserCardCvc,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "billing.address.country".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
- )
+ ),
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
]),
common: HashMap::new(),
}
),
+ ]),
+ },
+ ),
+ (
+ enums::PaymentMethodType::Credit,
+ ConnectorFields {
+ fields: HashMap::from([
+ (
+ enums::Connector::Aci,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Adyen,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Airwallex,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Authorizedotnet,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
(
- enums::Connector::Worldpay,
+ enums::Connector::Bambora,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from([
- (
- "payment_method_data.card.card_number".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_number".to_string(),
- display_name: "card_number".to_string(),
- field_type: enums::FieldType::UserCardNumber,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_exp_month".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_exp_month".to_string(),
- display_name: "card_exp_month".to_string(),
- field_type: enums::FieldType::UserCardExpiryMonth,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_exp_year".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_exp_year".to_string(),
- display_name: "card_exp_year".to_string(),
- field_type: enums::FieldType::UserCardExpiryYear,
- value: None,
- }
- )
- ]),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ ]
+ ),
common: HashMap::new(),
}
),
(
- enums::Connector::Zen,
+ enums::Connector::Bankofamerica,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from([
- (
- "payment_method_data.card.card_number".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_number".to_string(),
- display_name: "card_number".to_string(),
- field_type: enums::FieldType::UserCardNumber,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_exp_month".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_exp_month".to_string(),
- display_name: "card_exp_month".to_string(),
- field_type: enums::FieldType::UserCardExpiryMonth,
- value: None,
- }
- ),
- (
- "payment_method_data.card.card_exp_year".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_exp_year".to_string(),
- display_name: "card_exp_year".to_string(),
- field_type: enums::FieldType::UserCardExpiryYear,
- value: None,
- }
- ),
- (
- "email".to_string(),
- RequiredFieldInfo {
- required_field: "email".to_string(),
- display_name: "email".to_string(),
- field_type: enums::FieldType::UserEmailAddress,
- value: None,
- }
- ),
- ]),
- common: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserAddressState,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
+ ]
+ ),
}
),
- ]),
- },
- ),
- (
- enums::PaymentMethodType::Credit,
- ConnectorFields {
- fields: HashMap::from([
(
- enums::Connector::Aci,
+ enums::Connector::Billwerk,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
@@ -2377,35 +3343,16 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
- (
- "billing.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
+ )
]
),
}
),
(
- enums::Connector::Adyen,
+ enums::Connector::Bluesnap,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::new(),
- common: HashMap::from(
+ non_mandate: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2442,16 +3389,45 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
+ ),
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
)
]
),
+ common: HashMap::new(),
}
),
(
- enums::Connector::Airwallex,
+ enums::Connector::Boku,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2491,11 +3467,10 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common: HashMap::new(),
}
),
(
- enums::Connector::Authorizedotnet,
+ enums::Connector::Braintree,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
@@ -2542,7 +3517,7 @@ impl Default for super::settings::RequiredFields {
}
),
(
- enums::Connector::Bambora,
+ enums::Connector::Checkout,
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::from(
@@ -2582,35 +3557,38 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
+ )
+ ]
+ ),
+ common: HashMap::new(),
+ }
+ ),
+ (
+ enums::Connector::Coinbase,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
- ),
+ )
]
),
common: HashMap::new(),
}
),
(
- enums::Connector::Bankofamerica,
+ enums::Connector::Cybersource,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate:HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2648,20 +3626,11 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
- (
- "email".to_string(),
- RequiredFieldInfo {
- required_field: "email".to_string(),
- display_name: "email".to_string(),
- field_type: enums::FieldType::UserEmailAddress,
- value: None,
- }
- ),
(
"billing.address.first_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
@@ -2670,11 +3639,29 @@ impl Default for super::settings::RequiredFields {
"billing.address.last_name".to_string(),
RequiredFieldInfo {
required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
field_type: enums::FieldType::UserFullName,
value: None,
}
),
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
(
"billing.address.city".to_string(),
RequiredFieldInfo {
@@ -2714,26 +3701,96 @@ impl Default for super::settings::RequiredFields {
},
value: None,
}
+ )
+ ]
+ ),
+ }
+ ),
+ (
+ enums::Connector::Dlocal,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
),
(
- "billing.address.line1".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserAddressLine1,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
value: None,
}
),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ )
]
),
- common: HashMap::new(),
+ common:HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Bluesnap,
+ enums::Connector::DummyConnector1,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2770,44 +3827,66 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
+ )
+ ]
+ ),
+ }
+ ),
+ #[cfg(feature = "dummy_connector")]
+ (
+ enums::Connector::DummyConnector2,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
),
(
- "email".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "email".to_string(),
- display_name: "email".to_string(),
- field_type: enums::FieldType::UserEmailAddress,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "billing.address.first_name".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
),
(
- "billing.address.last_name".to_string(),
+ "payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
value: None,
}
)
]
),
- common: HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Checkout,
+ enums::Connector::DummyConnector3,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2847,34 +3926,15 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common: HashMap::new(),
- }
- ),
- (
- enums::Connector::Coinbase,
- RequiredFieldFinal {
- mandate: HashMap::new(),
- non_mandate: HashMap::from(
- [
- (
- "billing.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- )
- ]
- ),
- common: HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Cybersource,
+ enums::Connector::DummyConnector4,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -2911,93 +3971,114 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
+ )
+ ]
+ ),
+ }
+ ),
+ #[cfg(feature = "dummy_connector")]
+ (
+ enums::Connector::DummyConnector5,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
(
- "billing.address.first_name".to_string(),
+ "payment_method_data.card.card_number".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
value: None,
}
),
(
- "billing.address.last_name".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "email".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "email".to_string(),
- display_name: "email".to_string(),
- field_type: enums::FieldType::UserEmailAddress,
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
),
(
- "billing.address.line1".to_string(),
+ "payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.line1".to_string(),
- display_name: "line1".to_string(),
- field_type: enums::FieldType::UserAddressLine1,
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
+ )
+ ]
+ ),
+ }
+ ),
+ #[cfg(feature = "dummy_connector")]
+ (
+ enums::Connector::DummyConnector6,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
(
- "billing.address.city".to_string(),
+ "payment_method_data.card.card_number".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.city".to_string(),
- display_name: "city".to_string(),
- field_type: enums::FieldType::UserAddressCity,
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
value: None,
}
),
(
- "billing.address.state".to_string(),
+ "payment_method_data.card.card_exp_month".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.state".to_string(),
- display_name: "state".to_string(),
- field_type: enums::FieldType::UserAddressState,
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
value: None,
}
),
(
- "billing.address.zip".to_string(),
+ "payment_method_data.card.card_exp_year".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.zip".to_string(),
- display_name: "zip".to_string(),
- field_type: enums::FieldType::UserAddressPincode,
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
value: None,
}
),
(
- "billing.address.country".to_string(),
+ "payment_method_data.card.card_cvc".to_string(),
RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
value: None,
}
)
]
),
- common:HashMap::new(),
}
),
+ #[cfg(feature = "dummy_connector")]
(
- enums::Connector::Dlocal,
+ enums::Connector::DummyConnector7,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -3034,41 +4115,9 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserCardCvc,
value: None,
}
- ),
- (
- "billing.address.first_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.first_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.last_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.last_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
- (
- "billing.address.country".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.billing.address.country".to_string(),
- display_name: "country".to_string(),
- field_type: enums::FieldType::UserAddressCountry{
- options: vec![
- "ALL".to_string(),
- ]
- },
- value: None,
- }
)
]
),
- common:HashMap::new(),
}
),
(
@@ -3684,6 +4733,53 @@ impl Default for super::settings::RequiredFields {
),
}
),
+ (
+ enums::Connector::Nuvei,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
(
enums::Connector::Payme,
RequiredFieldFinal {
@@ -4028,7 +5124,55 @@ impl Default for super::settings::RequiredFields {
),
common: HashMap::new(),
}
- ),(
+ ),
+ (
+ enums::Connector::Square,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ )
+ ]
+ ),
+ }
+ ),
+ (
enums::Connector::Stax,
RequiredFieldFinal {
mandate: HashMap::new(),
|
2024-05-07T13:08:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
added missing card data fields for connectors Braintree,Square and Billwerk and DummyConnectors , fields are card_number, expiry_month, expiry_year and cvv
<!-- 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)?
-->
1. Create Merchant a Account
2. Create API key
3. Create payout/payment connector
4. check in payment method list
for square request:
```
curl --location 'http://127.0.0.1:8080/account/payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: {{apikey}}'
```
response payment method default fields for cards:
```
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"adyen"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"adyen"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"adyen"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"adyen"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
```
for dummy connector:
```
curl --location 'http://127.0.0.1:8080/account/payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: {{api-key}}'
```
fields for dummy connector:
```
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"phonypay"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"phonypay"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"phonypay"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"phonypay"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
```
and we will same these fields for other two connectors and dummy connectors
note: replace {{api-key}} with your actual api-key
## Checklist
<!-- Put an `x` in 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
|
cf0e3daeaa1dfdfa00d4cccdff5b845ac368bcb9
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4543
|
Bug: Revert "fix(users): add password validations"
|
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index f14610649f4..1cda969f780 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,5 +1,3 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
-pub const MAX_PASSWORD_LENGTH: usize = 70;
-pub const MIN_PASSWORD_LENGTH: usize = 8;
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index aed1bb02e72..b4b5df2f46c 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -158,32 +158,7 @@ pub struct UserPassword(Secret<String>);
impl UserPassword {
pub fn new(password: Secret<String>) -> UserResult<Self> {
let password = password.expose();
-
- let mut has_upper_case = false;
- let mut has_lower_case = false;
- let mut has_numeric_value = false;
- let mut has_special_character = false;
- let mut has_whitespace = false;
-
- for c in password.chars() {
- has_upper_case = has_upper_case || c.is_uppercase();
- has_lower_case = has_lower_case || c.is_lowercase();
- has_numeric_value = has_numeric_value || c.is_numeric();
- has_special_character =
- has_special_character || !(c.is_alphanumeric() && c.is_whitespace());
- has_whitespace = has_whitespace || c.is_whitespace();
- }
-
- let is_password_format_valid = has_upper_case
- && has_lower_case
- && has_numeric_value
- && has_special_character
- && !has_whitespace;
-
- let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH;
- let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH;
-
- if is_too_short || is_too_long || !is_password_format_valid {
+ if password.is_empty() {
Err(UserErrors::PasswordParsingError.into())
} else {
Ok(Self(password.into()))
|
2024-05-03T13:55:22Z
|
Reverts juspay/hyperswitch#4489
|
d5d9006fbd8e32f822f1e84d486b8a4483164baa
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4576
|
Bug: feat: Begin TOTP API
There should be an API which should tell whether the TOTP for the user is set or not, if not, the API should respond back with TOTP secrets (url, recovery_codes and secret) which FE uses to help user to setup TOTP in their authenticator application.
This API should work with the Decision manager and should be authenticated by the TOTP Single purpose token.
|
diff --git a/Cargo.lock b/Cargo.lock
index 84fdee38021..b823f9e5c96 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1430,6 +1430,12 @@ dependencies = [
"rustc-demangle",
]
+[[package]]
+name = "base32"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa"
+
[[package]]
name = "base64"
version = "0.13.1"
@@ -1559,7 +1565,7 @@ dependencies = [
"arrayvec",
"cc",
"cfg-if 1.0.0",
- "constant_time_eq",
+ "constant_time_eq 0.3.0",
]
[[package]]
@@ -2044,6 +2050,12 @@ dependencies = [
"tiny-keccak",
]
+[[package]]
+name = "constant_time_eq"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6"
+
[[package]]
name = "constant_time_eq"
version = "0.3.0"
@@ -5683,6 +5695,7 @@ dependencies = [
"thiserror",
"time",
"tokio 1.37.0",
+ "totp-rs",
"tracing-futures",
"unicode-segmentation",
"url",
@@ -7473,6 +7486,22 @@ dependencies = [
"tracing-futures",
]
+[[package]]
+name = "totp-rs"
+version = "5.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c4ae9724c5888c0417d2396037ed3b60665925624766416e3e342b6ba5dbd3f"
+dependencies = [
+ "base32",
+ "constant_time_eq 0.2.6",
+ "hmac",
+ "rand",
+ "sha1",
+ "sha2",
+ "url",
+ "urlencoding",
+]
+
[[package]]
name = "tower"
version = "0.4.13"
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index dab9ace3ac2..1d91a47bf56 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -10,13 +10,14 @@ use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
- AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
- CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
- InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
- RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest,
- SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
- UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
+ AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest,
+ ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse,
+ ForgotPasswordRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
+ GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest,
+ ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse,
+ SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse,
+ TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate,
+ VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -72,7 +73,8 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse,
TokenResponse,
- UserFromEmailRequest
+ UserFromEmailRequest,
+ BeginTotpResponse
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index b2128cc949c..0dde73d0545 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -236,8 +236,19 @@ pub enum TokenOrPayloadResponse<T> {
Token(TokenResponse),
Payload(T),
}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct BeginTotpResponse {
+ pub secret: Option<TotpSecret>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TotpSecret {
+ pub secret: Secret<String>,
+ pub totp_url: Secret<String>,
+ pub recovery_codes: Vec<Secret<String>>,
+}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 85a7e3d92df..d78a6b11489 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -18,8 +18,8 @@ pub mod diesel_exports {
DbRefundStatus as RefundStatus, DbRefundType as RefundType,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind,
- DbTransactionType as TransactionType, DbUserStatus as UserStatus,
- DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
+ DbTotpStatus as TotpStatus, DbTransactionType as TransactionType,
+ DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub use common_enums::*;
@@ -350,3 +350,26 @@ pub enum DashboardMetadata {
IsChangePasswordRequired,
OnboardingSurvey,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum TotpStatus {
+ Set,
+ InProgress,
+ #[default]
+ NotSet,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 24df19ff737..d7d10569f7f 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -44,6 +44,7 @@ pub mod routing_algorithm;
#[allow(unused_qualifications)]
pub mod schema;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
use diesel_impl::{DieselArray, OptionalDieselArray};
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index b839fcc9b63..335c2db916d 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -36,4 +36,5 @@ pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs
new file mode 100644
index 00000000000..42dfe223b1a
--- /dev/null
+++ b/crates/diesel_models/src/query/user_key_store.rs
@@ -0,0 +1,24 @@
+use diesel::{associations::HasTable, ExpressionMethods};
+
+use super::generics;
+use crate::{
+ schema::user_key_store::dsl,
+ user_key_store::{UserKeyStore, UserKeyStoreNew},
+ PgPooledConn, StorageResult,
+};
+
+impl UserKeyStoreNew {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl UserKeyStore {
+ pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::user_id.eq(user_id.to_owned()),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 70a227a310a..20296adb65c 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1149,6 +1149,18 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ user_key_store (user_id) {
+ #[max_length = 64]
+ user_id -> Varchar,
+ key -> Bytea,
+ created_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1192,6 +1204,9 @@ diesel::table! {
last_modified_at -> Timestamp,
#[max_length = 64]
preferred_merchant_id -> Nullable<Varchar>,
+ totp_status -> TotpStatus,
+ totp_secret -> Nullable<Bytea>,
+ totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
}
}
@@ -1232,6 +1247,7 @@ diesel::allow_tables_to_appear_in_same_query!(
reverse_lookup,
roles,
routing_algorithm,
+ user_key_store,
user_roles,
users,
);
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 850619f8af6..6a040e41468 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -3,7 +3,9 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use masking::Secret;
use time::PrimitiveDateTime;
-use crate::schema::users;
+use crate::{
+ diesel_impl::OptionalDieselArray, encryption::Encryption, enums::TotpStatus, schema::users,
+};
pub mod dashboard_metadata;
@@ -20,6 +22,10 @@ pub struct User {
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub preferred_merchant_id: Option<String>,
+ pub totp_status: TotpStatus,
+ pub totp_secret: Option<Encryption>,
+ #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)]
+ pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -36,6 +42,9 @@ pub struct UserNew {
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
pub preferred_merchant_id: Option<String>,
+ pub totp_status: TotpStatus,
+ pub totp_secret: Option<Encryption>,
+ pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -47,6 +56,9 @@ pub struct UserUpdateInternal {
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
preferred_merchant_id: Option<String>,
+ totp_status: Option<TotpStatus>,
+ totp_secret: Option<Encryption>,
+ totp_recovery_codes: Option<Vec<Secret<String>>>,
last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -58,6 +70,11 @@ pub enum UserUpdate {
is_verified: Option<bool>,
preferred_merchant_id: Option<String>,
},
+ TotpUpdate {
+ totp_status: Option<TotpStatus>,
+ totp_secret: Option<Encryption>,
+ totp_recovery_codes: Option<Vec<Secret<String>>>,
+ },
PasswordUpdate {
password: Option<Secret<String>>,
},
@@ -73,6 +90,9 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified: Some(true),
last_modified_at,
preferred_merchant_id: None,
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
last_password_modified_at: None,
},
UserUpdate::AccountUpdate {
@@ -85,6 +105,24 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified,
last_modified_at,
preferred_merchant_id,
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
+ last_password_modified_at: None,
+ },
+ UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => Self {
+ name: None,
+ password: None,
+ is_verified: None,
+ last_modified_at,
+ preferred_merchant_id: None,
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
last_password_modified_at: None,
},
UserUpdate::PasswordUpdate { password } => Self {
@@ -94,6 +132,9 @@ impl From<UserUpdate> for UserUpdateInternal {
last_modified_at,
preferred_merchant_id: None,
last_password_modified_at: Some(last_modified_at),
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
},
}
}
diff --git a/crates/diesel_models/src/user_key_store.rs b/crates/diesel_models/src/user_key_store.rs
new file mode 100644
index 00000000000..a35b4d9d169
--- /dev/null
+++ b/crates/diesel_models/src/user_key_store.rs
@@ -0,0 +1,21 @@
+use diesel::{Identifiable, Insertable, Queryable};
+use time::PrimitiveDateTime;
+
+use crate::{encryption::Encryption, schema::user_key_store};
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable)]
+#[diesel(table_name = user_key_store)]
+#[diesel(primary_key(user_id))]
+pub struct UserKeyStore {
+ pub user_id: String,
+ pub key: Encryption,
+ pub created_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Insertable)]
+#[diesel(table_name = user_key_store)]
+pub struct UserKeyStoreNew {
+ pub user_id: String,
+ pub key: Encryption,
+ pub created_at: PrimitiveDateTime,
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 7ff47b927d8..144d6f07988 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -126,6 +126,7 @@ isocountry = "0.3.2"
iso_currency = "0.4.4"
actix-http = "3.6.0"
events = { version = "0.1.0", path = "../events" }
+totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"]}
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index f14610649f4..8d6aa6265d8 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,5 +1,14 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
+pub const RECOVERY_CODES_COUNT: usize = 8;
+pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
+pub const TOTP_ISSUER_NAME: &str = "Hyperswitch";
+/// The number of digits composing the auth code.
+pub const TOTP_DIGITS: usize = 6;
+/// Duration in seconds of a step.
+pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
+/// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids.
+pub const TOTP_TOLERANCE: u8 = 1;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e51ad6120c9..e01ed4b1a23 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1,9 +1,13 @@
use api_models::user::{self as user_api, InviteMultipleUserResponse};
#[cfg(feature = "email")]
use diesel_models::user_role::UserRoleUpdate;
-use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew};
+use diesel_models::{
+ enums::{TotpStatus, UserStatus},
+ user as storage_user,
+ user_role::UserRoleNew,
+};
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+use masking::{ExposeInterface, PeekInterface};
#[cfg(feature = "email")]
use router_env::env;
use router_env::logger;
@@ -1581,3 +1585,60 @@ pub async fn user_from_email(
};
auth::cookies::set_cookie_response(response, token)
}
+
+pub async fn begin_totp(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+) -> UserResponse<user_api::BeginTotpResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if user_from_db.get_totp_status() == TotpStatus::Set {
+ return Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
+ secret: None,
+ }));
+ }
+
+ let totp = utils::user::generate_default_totp(user_from_db.get_email(), None)?;
+ let recovery_codes = domain::RecoveryCodes::generate_new();
+
+ let key_store = user_from_db.get_or_create_key_store(&state).await?;
+
+ state
+ .store
+ .update_user_by_user_id(
+ user_from_db.get_user_id(),
+ storage_user::UserUpdate::TotpUpdate {
+ totp_status: Some(TotpStatus::InProgress),
+ totp_secret: Some(
+ // TODO: Impl conversion trait for User and move this there
+ domain::types::encrypt::<String, masking::WithType>(
+ totp.get_secret_base32().into(),
+ key_store.key.peek(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into(),
+ ),
+ totp_recovery_codes: Some(
+ recovery_codes
+ .get_hashed()
+ .change_context(UserErrors::InternalServerError)?,
+ ),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
+ secret: Some(user_api::TotpSecret {
+ secret: totp.get_secret_base32().into(),
+ totp_url: totp.get_url().into(),
+ recovery_codes: recovery_codes.into_inner(),
+ }),
+ }))
+}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index ca9432fcba9..c34bcaa1e38 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -33,6 +33,7 @@ pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
use diesel_models::{
@@ -118,6 +119,7 @@ pub trait StorageInterface:
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ role::RoleInterface
+ + user_key_store::UserKeyStoreInterface
+ authentication::AuthenticationInterface
+ 'static
{
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0aaa47365fc..4a9ab7fc8f6 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -32,6 +32,7 @@ use super::{
dashboard_metadata::DashboardMetadataInterface,
role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, UserInterface},
+ user_key_store::UserKeyStoreInterface,
user_role::UserRoleInterface,
};
#[cfg(feature = "payouts")]
@@ -2743,3 +2744,26 @@ impl RoleInterface for KafkaStore {
self.diesel_store.list_all_roles(merchant_id, org_id).await
}
}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for KafkaStore {
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.diesel_store
+ .insert_user_key_store(user_key_store, key)
+ .await
+ }
+
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.diesel_store
+ .get_user_key_store_by_user_id(user_id, key)
+ .await
+ }
+}
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index 9ec7cf6fab4..200513ae8d0 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -162,6 +162,9 @@ impl UserInterface for MockDb {
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
preferred_merchant_id: user_data.preferred_merchant_id,
+ totp_status: user_data.totp_status,
+ totp_secret: user_data.totp_secret,
+ totp_recovery_codes: user_data.totp_recovery_codes,
last_password_modified_at: user_data.last_password_modified_at,
};
users.push(user.clone());
@@ -229,6 +232,18 @@ impl UserInterface for MockDb {
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => storage::User {
+ totp_status: totp_status.unwrap_or(user.totp_status),
+ totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
+ totp_recovery_codes: totp_recovery_codes
+ .clone()
+ .or(user.totp_recovery_codes.clone()),
+ ..user.to_owned()
+ },
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: password.clone().unwrap_or(user.password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
@@ -272,6 +287,18 @@ impl UserInterface for MockDb {
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => storage::User {
+ totp_status: totp_status.unwrap_or(user.totp_status),
+ totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
+ totp_recovery_codes: totp_recovery_codes
+ .clone()
+ .or(user.totp_recovery_codes.clone()),
+ ..user.to_owned()
+ },
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: password.clone().unwrap_or(user.password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs
new file mode 100644
index 00000000000..e08d17d280e
--- /dev/null
+++ b/crates/router/src/db/user_key_store.rs
@@ -0,0 +1,121 @@
+use common_utils::errors::CustomResult;
+use error_stack::{report, ResultExt};
+use masking::Secret;
+use router_env::{instrument, tracing};
+use storage_impl::MockDb;
+
+use crate::{
+ connection,
+ core::errors,
+ services::Store,
+ types::domain::{
+ self,
+ behaviour::{Conversion, ReverseConversion},
+ },
+};
+
+#[async_trait::async_trait]
+pub trait UserKeyStoreInterface {
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
+
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for Store {
+ #[instrument(skip_all)]
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ user_key_store
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for MockDb {
+ #[instrument(skip_all)]
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let mut locked_user_key_store = self.user_key_store.lock().await;
+
+ if locked_user_key_store
+ .iter()
+ .any(|user_key| user_key.user_id == user_key_store.user_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "user_key_store",
+ key: Some(user_key_store.user_id.clone()),
+ })?;
+ }
+
+ let user_key_store = Conversion::convert(user_key_store)
+ .await
+ .change_context(errors::StorageError::MockDbError)?;
+ locked_user_key_store.push(user_key_store.clone());
+
+ user_key_store
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.user_key_store
+ .lock()
+ .await
+ .iter()
+ .find(|user_key_store| user_key_store.user_id == user_id)
+ .cloned()
+ .ok_or(errors::StorageError::ValueNotFound(format!(
+ "No user_key_store is found for user_id={}",
+ user_id
+ )))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 857da69d4b3..cff4fc67db3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1197,7 +1197,8 @@ impl User {
web::resource("/data")
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
- );
+ )
+ .service(web::resource("/totp/begin").route(web::get().to(totp_begin)));
#[cfg(feature = "email")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5f8346a8f23..5bef68073f0 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -210,7 +210,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
- | Flow::UpdateUserAccountDetails => Self::User,
+ | Flow::UpdateUserAccountDetails
+ | Flow::TotpBegin => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index f990438b2f1..db12729d01a 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -612,3 +612,17 @@ pub async fn user_from_email(
))
.await
}
+
+pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::TotpBegin;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::begin_totp(state, user),
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs
index e5f6b8c9660..d18ae0d0190 100644
--- a/crates/router/src/types/domain.rs
+++ b/crates/router/src/types/domain.rs
@@ -9,6 +9,7 @@ pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
pub mod user;
+pub mod user_key_store;
pub use address::*;
pub use customer::*;
@@ -19,3 +20,4 @@ pub use merchant_key_store::*;
pub use payments::*;
#[cfg(feature = "olap")]
pub use user::*;
+pub use user_key_store::*;
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 7e1a1eee3e8..00881626c1c 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -6,7 +6,7 @@ use api_models::{
use common_enums::TokenPurpose;
use common_utils::{errors::CustomResult, pii};
use diesel_models::{
- enums::UserStatus,
+ enums::{TotpStatus, UserStatus},
organization as diesel_org,
organization::Organization,
user as storage_user,
@@ -15,6 +15,7 @@ use diesel_models::{
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
use once_cell::sync::Lazy;
+use rand::distributions::{Alphanumeric, DistString};
use router_env::env;
use unicode_segmentation::UnicodeSegmentation;
@@ -26,7 +27,7 @@ use crate::{
},
db::StorageInterface,
routes::AppState,
- services::{authentication as auth, authentication::UserFromToken, authorization::info},
+ services::{self, authentication as auth, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
utils::{self, user::password},
};
@@ -35,6 +36,8 @@ pub mod dashboard_metadata;
pub mod decision_manager;
pub use decision_manager::*;
+use super::{types as domain_types, UserKeyStore};
+
#[derive(Clone)]
pub struct UserName(Secret<String>);
@@ -863,6 +866,49 @@ impl UserFromStorage {
)
}
}
+
+ pub async fn get_or_create_key_store(&self, state: &AppState) -> UserResult<UserKeyStore> {
+ let master_key = state.store.get_master_key();
+ let key_store_result = state
+ .store
+ .get_user_key_store_by_user_id(self.get_user_id(), &master_key.to_vec().into())
+ .await;
+
+ if let Ok(key_store) = key_store_result {
+ Ok(key_store)
+ } else if key_store_result
+ .as_ref()
+ .map_err(|e| e.current_context().is_db_not_found())
+ .err()
+ .unwrap_or(false)
+ {
+ let key = services::generate_aes256_key()
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Unable to generate aes 256 key")?;
+
+ let key_store = UserKeyStore {
+ user_id: self.get_user_id().to_string(),
+ key: domain_types::encrypt(key.to_vec().into(), master_key)
+ .await
+ .change_context(UserErrors::InternalServerError)?,
+ created_at: common_utils::date_time::now(),
+ };
+ state
+ .store
+ .insert_user_key_store(key_store, &master_key.to_vec().into())
+ .await
+ .change_context(UserErrors::InternalServerError)
+ } else {
+ Err(key_store_result
+ .err()
+ .map(|e| e.change_context(UserErrors::InternalServerError))
+ .unwrap_or(UserErrors::InternalServerError.into()))
+ }
+ }
+
+ pub fn get_totp_status(&self) -> TotpStatus {
+ self.0.totp_status
+ }
}
impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
@@ -1031,3 +1077,36 @@ impl RoleName {
self.0
}
}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct RecoveryCodes(pub Vec<Secret<String>>);
+
+impl RecoveryCodes {
+ pub fn generate_new() -> Self {
+ let mut rand = rand::thread_rng();
+ let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT)
+ .map(|_| {
+ let code_part_1 =
+ Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
+ let code_part_2 =
+ Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
+
+ Secret::new(format!("{}-{}", code_part_1, code_part_2))
+ })
+ .collect::<Vec<_>>();
+
+ Self(recovery_codes)
+ }
+
+ pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> {
+ self.0
+ .iter()
+ .cloned()
+ .map(password::generate_password_hash)
+ .collect::<Result<Vec<_>, _>>()
+ }
+
+ pub fn into_inner(self) -> Vec<Secret<String>> {
+ self.0
+ }
+}
diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs
new file mode 100644
index 00000000000..4c1427d58dc
--- /dev/null
+++ b/crates/router/src/types/domain/user_key_store.rs
@@ -0,0 +1,59 @@
+use common_utils::{
+ crypto::{Encryptable, GcmAes256},
+ date_time,
+};
+use error_stack::ResultExt;
+use masking::{PeekInterface, Secret};
+use time::PrimitiveDateTime;
+
+use crate::{
+ errors::{CustomResult, ValidationError},
+ types::domain::types::TypeEncryption,
+};
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct UserKeyStore {
+ pub user_id: String,
+ pub key: Encryptable<Secret<Vec<u8>>>,
+ pub created_at: PrimitiveDateTime,
+}
+
+#[async_trait::async_trait]
+impl super::behaviour::Conversion for UserKeyStore {
+ type DstType = diesel_models::user_key_store::UserKeyStore;
+ type NewDstType = diesel_models::user_key_store::UserKeyStoreNew;
+
+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
+ Ok(diesel_models::user_key_store::UserKeyStore {
+ key: self.key.into(),
+ user_id: self.user_id,
+ created_at: self.created_at,
+ })
+ }
+
+ async fn convert_back(
+ item: Self::DstType,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Self, ValidationError>
+ where
+ Self: Sized,
+ {
+ Ok(Self {
+ key: Encryptable::decrypt(item.key, key.peek(), GcmAes256)
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?,
+ user_id: item.user_id,
+ created_at: item.created_at,
+ })
+ }
+
+ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
+ Ok(diesel_models::user_key_store::UserKeyStoreNew {
+ user_id: self.user_id,
+ key: self.key.into(),
+ created_at: date_time::now(),
+ })
+ }
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 33e9aa6769c..4980958c9ac 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,12 +1,14 @@
use std::collections::HashMap;
use api_models::user as user_api;
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, pii};
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::ResultExt;
-use masking::Secret;
+use masking::ExposeInterface;
+use totp_rs::{Algorithm, TOTP};
use crate::{
+ consts,
core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
services::{
@@ -74,7 +76,7 @@ pub async fn generate_jwt_auth_token(
state: &AppState,
user: &UserFromStorage,
user_role: &UserRole,
-) -> UserResult<Secret<String>> {
+) -> UserResult<masking::Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
user_role.merchant_id.clone(),
@@ -83,7 +85,7 @@ pub async fn generate_jwt_auth_token(
user_role.org_id.clone(),
)
.await?;
- Ok(Secret::new(token))
+ Ok(masking::Secret::new(token))
}
pub async fn generate_jwt_auth_token_with_custom_role_attributes(
@@ -92,7 +94,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
merchant_id: String,
org_id: String,
role_id: String,
-) -> UserResult<Secret<String>> {
+) -> UserResult<masking::Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
merchant_id,
@@ -101,14 +103,14 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
org_id,
)
.await?;
- Ok(Secret::new(token))
+ Ok(masking::Secret::new(token))
}
pub fn get_dashboard_entry_response(
state: &AppState,
user: UserFromStorage,
user_role: UserRole,
- token: Secret<String>,
+ token: masking::Secret<String>,
) -> UserResult<user_api::DashboardEntryResponse> {
let verification_days_left = get_verification_days_left(state, &user)?;
@@ -185,9 +187,31 @@ pub async fn get_user_from_db_by_email(
.map(UserFromStorage::from)
}
-pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> {
+pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> masking::Secret<String> {
match resp {
user_api::SignInResponse::DashboardEntry(data) => data.token.clone(),
user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
}
}
+
+pub fn generate_default_totp(
+ email: pii::Email,
+ secret: Option<masking::Secret<String>>,
+) -> UserResult<TOTP> {
+ let secret = secret
+ .map(|sec| totp_rs::Secret::Encoded(sec.expose()))
+ .unwrap_or_else(totp_rs::Secret::generate_secret)
+ .to_bytes()
+ .change_context(UserErrors::InternalServerError)?;
+
+ TOTP::new(
+ Algorithm::SHA1,
+ consts::user::TOTP_DIGITS,
+ consts::user::TOTP_TOLERANCE,
+ consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
+ secret,
+ Some(consts::user::TOTP_ISSUER_NAME.to_string()),
+ email.expose().expose(),
+ )
+ .change_context(UserErrors::InternalServerError)
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b360d20fed1..b3252302413 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -396,6 +396,8 @@ pub enum Flow {
UpdateRole,
/// User email flow start
UserFromEmail,
+ /// Begin TOTP
+ TotpBegin,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 3657201f878..0ada6513ff0 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -57,6 +57,7 @@ pub struct MockDb {
pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>,
pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>,
pub roles: Arc<Mutex<Vec<store::role::Role>>>,
+ pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,
}
impl MockDb {
@@ -100,6 +101,7 @@ impl MockDb {
payouts: Default::default(),
authentications: Default::default(),
roles: Default::default(),
+ user_key_store: Default::default(),
})
}
}
diff --git a/migrations/2024-05-06-105026_user_key_store_table/down.sql b/migrations/2024-05-06-105026_user_key_store_table/down.sql
new file mode 100644
index 00000000000..63df9500997
--- /dev/null
+++ b/migrations/2024-05-06-105026_user_key_store_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+DROP TABLE IF EXISTS user_key_store;
diff --git a/migrations/2024-05-06-105026_user_key_store_table/up.sql b/migrations/2024-05-06-105026_user_key_store_table/up.sql
new file mode 100644
index 00000000000..48147e6f597
--- /dev/null
+++ b/migrations/2024-05-06-105026_user_key_store_table/up.sql
@@ -0,0 +1,6 @@
+-- Your SQL goes here
+CREATE TABLE IF NOT EXISTS user_key_store (
+ user_id VARCHAR(64) PRIMARY KEY,
+ key bytea NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT now()
+);
diff --git a/migrations/2024-05-07-080628_user_totp/down.sql b/migrations/2024-05-07-080628_user_totp/down.sql
new file mode 100644
index 00000000000..d8e5840e35c
--- /dev/null
+++ b/migrations/2024-05-07-080628_user_totp/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users DROP COLUMN totp_status;
+ALTER TABLE users DROP COLUMN totp_secret;
+ALTER TABLE users DROP COLUMN totp_recovery_codes;
+
+DROP TYPE "TotpStatus";
diff --git a/migrations/2024-05-07-080628_user_totp/up.sql b/migrations/2024-05-07-080628_user_totp/up.sql
new file mode 100644
index 00000000000..770a3fbd4c5
--- /dev/null
+++ b/migrations/2024-05-07-080628_user_totp/up.sql
@@ -0,0 +1,10 @@
+-- Your SQL goes here
+CREATE TYPE "TotpStatus" AS ENUM (
+ 'set',
+ 'in_progress',
+ 'not_set'
+);
+
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_status "TotpStatus" DEFAULT 'not_set' NOT NULL;
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret bytea DEFAULT NULL;
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_recovery_codes TEXT[] DEFAULT NULL;
|
2024-05-07T17:02:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- This PR adds a new table `user_key_store`, which stores the encryption keys for the user's secrets.
- A new API `begin_totp` has been added, which will check if the user has setup the TOTP or not, and respond with TOTP secret which user has to scan to setup the TOTP in his authenticator application if user didn't setup TOTP.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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 #4575
Closes #4576
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```curl
curl --location 'http://localhost:8080/user/totp/begin' \
--header 'Authorization: Bearer SPT with purpose as totp' \
```
If user hasn't setup TOTP, then the response should be like this:
```json
{
"secret": {
"secret": "EL63X66IYIK2KHIH7DPRYLQTKLUGZMN2",
"totp_url": "otpauth://totp/Hyperswitch:{user_email}?secret=EL63X66IYIK2KHIH7DPRYLQTKLUGZMN2&issuer=Hyperswitch",
"recovery_codes": [
"UNiW-lqXn",
"CpSF-c1TP",
"m2zI-hp4w",
"NGFE-ypVh",
"YxlU-QrNj",
"Nsdu-89FC",
"7OZM-Z4Av",
"LJLD-X80O"
]
}
}
```
If user has completed TOTP setup, then the secret will be null:
```json
{
"secret": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
339da8b0c9a1e388b65ff5d82a162e758c85ec6b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4575
|
Bug: feat: User key store
As we are focusing on security aspects of users, we are going to encrypt emails of the users and also create 2FA.
For these two, we need to encrypt some data and store it, and to be able to decrypt that data, we need to store the keys. As keys should not be same for all the users, we need to have a table which keeps track of user keys.
|
diff --git a/Cargo.lock b/Cargo.lock
index 84fdee38021..b823f9e5c96 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1430,6 +1430,12 @@ dependencies = [
"rustc-demangle",
]
+[[package]]
+name = "base32"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa"
+
[[package]]
name = "base64"
version = "0.13.1"
@@ -1559,7 +1565,7 @@ dependencies = [
"arrayvec",
"cc",
"cfg-if 1.0.0",
- "constant_time_eq",
+ "constant_time_eq 0.3.0",
]
[[package]]
@@ -2044,6 +2050,12 @@ dependencies = [
"tiny-keccak",
]
+[[package]]
+name = "constant_time_eq"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6"
+
[[package]]
name = "constant_time_eq"
version = "0.3.0"
@@ -5683,6 +5695,7 @@ dependencies = [
"thiserror",
"time",
"tokio 1.37.0",
+ "totp-rs",
"tracing-futures",
"unicode-segmentation",
"url",
@@ -7473,6 +7486,22 @@ dependencies = [
"tracing-futures",
]
+[[package]]
+name = "totp-rs"
+version = "5.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c4ae9724c5888c0417d2396037ed3b60665925624766416e3e342b6ba5dbd3f"
+dependencies = [
+ "base32",
+ "constant_time_eq 0.2.6",
+ "hmac",
+ "rand",
+ "sha1",
+ "sha2",
+ "url",
+ "urlencoding",
+]
+
[[package]]
name = "tower"
version = "0.4.13"
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index dab9ace3ac2..1d91a47bf56 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -10,13 +10,14 @@ use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
- AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
- CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
- InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
- RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest,
- SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
- UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
+ AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest,
+ ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse,
+ ForgotPasswordRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
+ GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest,
+ ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse,
+ SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse,
+ TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate,
+ VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -72,7 +73,8 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse,
TokenResponse,
- UserFromEmailRequest
+ UserFromEmailRequest,
+ BeginTotpResponse
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index b2128cc949c..0dde73d0545 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -236,8 +236,19 @@ pub enum TokenOrPayloadResponse<T> {
Token(TokenResponse),
Payload(T),
}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct BeginTotpResponse {
+ pub secret: Option<TotpSecret>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TotpSecret {
+ pub secret: Secret<String>,
+ pub totp_url: Secret<String>,
+ pub recovery_codes: Vec<Secret<String>>,
+}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 85a7e3d92df..d78a6b11489 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -18,8 +18,8 @@ pub mod diesel_exports {
DbRefundStatus as RefundStatus, DbRefundType as RefundType,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind,
- DbTransactionType as TransactionType, DbUserStatus as UserStatus,
- DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
+ DbTotpStatus as TotpStatus, DbTransactionType as TransactionType,
+ DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub use common_enums::*;
@@ -350,3 +350,26 @@ pub enum DashboardMetadata {
IsChangePasswordRequired,
OnboardingSurvey,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum TotpStatus {
+ Set,
+ InProgress,
+ #[default]
+ NotSet,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 24df19ff737..d7d10569f7f 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -44,6 +44,7 @@ pub mod routing_algorithm;
#[allow(unused_qualifications)]
pub mod schema;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
use diesel_impl::{DieselArray, OptionalDieselArray};
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index b839fcc9b63..335c2db916d 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -36,4 +36,5 @@ pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs
new file mode 100644
index 00000000000..42dfe223b1a
--- /dev/null
+++ b/crates/diesel_models/src/query/user_key_store.rs
@@ -0,0 +1,24 @@
+use diesel::{associations::HasTable, ExpressionMethods};
+
+use super::generics;
+use crate::{
+ schema::user_key_store::dsl,
+ user_key_store::{UserKeyStore, UserKeyStoreNew},
+ PgPooledConn, StorageResult,
+};
+
+impl UserKeyStoreNew {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl UserKeyStore {
+ pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::user_id.eq(user_id.to_owned()),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 70a227a310a..20296adb65c 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1149,6 +1149,18 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ user_key_store (user_id) {
+ #[max_length = 64]
+ user_id -> Varchar,
+ key -> Bytea,
+ created_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1192,6 +1204,9 @@ diesel::table! {
last_modified_at -> Timestamp,
#[max_length = 64]
preferred_merchant_id -> Nullable<Varchar>,
+ totp_status -> TotpStatus,
+ totp_secret -> Nullable<Bytea>,
+ totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
}
}
@@ -1232,6 +1247,7 @@ diesel::allow_tables_to_appear_in_same_query!(
reverse_lookup,
roles,
routing_algorithm,
+ user_key_store,
user_roles,
users,
);
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 850619f8af6..6a040e41468 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -3,7 +3,9 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use masking::Secret;
use time::PrimitiveDateTime;
-use crate::schema::users;
+use crate::{
+ diesel_impl::OptionalDieselArray, encryption::Encryption, enums::TotpStatus, schema::users,
+};
pub mod dashboard_metadata;
@@ -20,6 +22,10 @@ pub struct User {
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub preferred_merchant_id: Option<String>,
+ pub totp_status: TotpStatus,
+ pub totp_secret: Option<Encryption>,
+ #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)]
+ pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -36,6 +42,9 @@ pub struct UserNew {
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
pub preferred_merchant_id: Option<String>,
+ pub totp_status: TotpStatus,
+ pub totp_secret: Option<Encryption>,
+ pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -47,6 +56,9 @@ pub struct UserUpdateInternal {
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
preferred_merchant_id: Option<String>,
+ totp_status: Option<TotpStatus>,
+ totp_secret: Option<Encryption>,
+ totp_recovery_codes: Option<Vec<Secret<String>>>,
last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -58,6 +70,11 @@ pub enum UserUpdate {
is_verified: Option<bool>,
preferred_merchant_id: Option<String>,
},
+ TotpUpdate {
+ totp_status: Option<TotpStatus>,
+ totp_secret: Option<Encryption>,
+ totp_recovery_codes: Option<Vec<Secret<String>>>,
+ },
PasswordUpdate {
password: Option<Secret<String>>,
},
@@ -73,6 +90,9 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified: Some(true),
last_modified_at,
preferred_merchant_id: None,
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
last_password_modified_at: None,
},
UserUpdate::AccountUpdate {
@@ -85,6 +105,24 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified,
last_modified_at,
preferred_merchant_id,
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
+ last_password_modified_at: None,
+ },
+ UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => Self {
+ name: None,
+ password: None,
+ is_verified: None,
+ last_modified_at,
+ preferred_merchant_id: None,
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
last_password_modified_at: None,
},
UserUpdate::PasswordUpdate { password } => Self {
@@ -94,6 +132,9 @@ impl From<UserUpdate> for UserUpdateInternal {
last_modified_at,
preferred_merchant_id: None,
last_password_modified_at: Some(last_modified_at),
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
},
}
}
diff --git a/crates/diesel_models/src/user_key_store.rs b/crates/diesel_models/src/user_key_store.rs
new file mode 100644
index 00000000000..a35b4d9d169
--- /dev/null
+++ b/crates/diesel_models/src/user_key_store.rs
@@ -0,0 +1,21 @@
+use diesel::{Identifiable, Insertable, Queryable};
+use time::PrimitiveDateTime;
+
+use crate::{encryption::Encryption, schema::user_key_store};
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable)]
+#[diesel(table_name = user_key_store)]
+#[diesel(primary_key(user_id))]
+pub struct UserKeyStore {
+ pub user_id: String,
+ pub key: Encryption,
+ pub created_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Insertable)]
+#[diesel(table_name = user_key_store)]
+pub struct UserKeyStoreNew {
+ pub user_id: String,
+ pub key: Encryption,
+ pub created_at: PrimitiveDateTime,
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 7ff47b927d8..144d6f07988 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -126,6 +126,7 @@ isocountry = "0.3.2"
iso_currency = "0.4.4"
actix-http = "3.6.0"
events = { version = "0.1.0", path = "../events" }
+totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"]}
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index f14610649f4..8d6aa6265d8 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,5 +1,14 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
+pub const RECOVERY_CODES_COUNT: usize = 8;
+pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
+pub const TOTP_ISSUER_NAME: &str = "Hyperswitch";
+/// The number of digits composing the auth code.
+pub const TOTP_DIGITS: usize = 6;
+/// Duration in seconds of a step.
+pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
+/// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids.
+pub const TOTP_TOLERANCE: u8 = 1;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e51ad6120c9..e01ed4b1a23 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1,9 +1,13 @@
use api_models::user::{self as user_api, InviteMultipleUserResponse};
#[cfg(feature = "email")]
use diesel_models::user_role::UserRoleUpdate;
-use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew};
+use diesel_models::{
+ enums::{TotpStatus, UserStatus},
+ user as storage_user,
+ user_role::UserRoleNew,
+};
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+use masking::{ExposeInterface, PeekInterface};
#[cfg(feature = "email")]
use router_env::env;
use router_env::logger;
@@ -1581,3 +1585,60 @@ pub async fn user_from_email(
};
auth::cookies::set_cookie_response(response, token)
}
+
+pub async fn begin_totp(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+) -> UserResponse<user_api::BeginTotpResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if user_from_db.get_totp_status() == TotpStatus::Set {
+ return Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
+ secret: None,
+ }));
+ }
+
+ let totp = utils::user::generate_default_totp(user_from_db.get_email(), None)?;
+ let recovery_codes = domain::RecoveryCodes::generate_new();
+
+ let key_store = user_from_db.get_or_create_key_store(&state).await?;
+
+ state
+ .store
+ .update_user_by_user_id(
+ user_from_db.get_user_id(),
+ storage_user::UserUpdate::TotpUpdate {
+ totp_status: Some(TotpStatus::InProgress),
+ totp_secret: Some(
+ // TODO: Impl conversion trait for User and move this there
+ domain::types::encrypt::<String, masking::WithType>(
+ totp.get_secret_base32().into(),
+ key_store.key.peek(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into(),
+ ),
+ totp_recovery_codes: Some(
+ recovery_codes
+ .get_hashed()
+ .change_context(UserErrors::InternalServerError)?,
+ ),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
+ secret: Some(user_api::TotpSecret {
+ secret: totp.get_secret_base32().into(),
+ totp_url: totp.get_url().into(),
+ recovery_codes: recovery_codes.into_inner(),
+ }),
+ }))
+}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index ca9432fcba9..c34bcaa1e38 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -33,6 +33,7 @@ pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
use diesel_models::{
@@ -118,6 +119,7 @@ pub trait StorageInterface:
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ role::RoleInterface
+ + user_key_store::UserKeyStoreInterface
+ authentication::AuthenticationInterface
+ 'static
{
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0aaa47365fc..4a9ab7fc8f6 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -32,6 +32,7 @@ use super::{
dashboard_metadata::DashboardMetadataInterface,
role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, UserInterface},
+ user_key_store::UserKeyStoreInterface,
user_role::UserRoleInterface,
};
#[cfg(feature = "payouts")]
@@ -2743,3 +2744,26 @@ impl RoleInterface for KafkaStore {
self.diesel_store.list_all_roles(merchant_id, org_id).await
}
}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for KafkaStore {
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.diesel_store
+ .insert_user_key_store(user_key_store, key)
+ .await
+ }
+
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.diesel_store
+ .get_user_key_store_by_user_id(user_id, key)
+ .await
+ }
+}
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index 9ec7cf6fab4..200513ae8d0 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -162,6 +162,9 @@ impl UserInterface for MockDb {
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
preferred_merchant_id: user_data.preferred_merchant_id,
+ totp_status: user_data.totp_status,
+ totp_secret: user_data.totp_secret,
+ totp_recovery_codes: user_data.totp_recovery_codes,
last_password_modified_at: user_data.last_password_modified_at,
};
users.push(user.clone());
@@ -229,6 +232,18 @@ impl UserInterface for MockDb {
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => storage::User {
+ totp_status: totp_status.unwrap_or(user.totp_status),
+ totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
+ totp_recovery_codes: totp_recovery_codes
+ .clone()
+ .or(user.totp_recovery_codes.clone()),
+ ..user.to_owned()
+ },
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: password.clone().unwrap_or(user.password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
@@ -272,6 +287,18 @@ impl UserInterface for MockDb {
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => storage::User {
+ totp_status: totp_status.unwrap_or(user.totp_status),
+ totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
+ totp_recovery_codes: totp_recovery_codes
+ .clone()
+ .or(user.totp_recovery_codes.clone()),
+ ..user.to_owned()
+ },
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: password.clone().unwrap_or(user.password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs
new file mode 100644
index 00000000000..e08d17d280e
--- /dev/null
+++ b/crates/router/src/db/user_key_store.rs
@@ -0,0 +1,121 @@
+use common_utils::errors::CustomResult;
+use error_stack::{report, ResultExt};
+use masking::Secret;
+use router_env::{instrument, tracing};
+use storage_impl::MockDb;
+
+use crate::{
+ connection,
+ core::errors,
+ services::Store,
+ types::domain::{
+ self,
+ behaviour::{Conversion, ReverseConversion},
+ },
+};
+
+#[async_trait::async_trait]
+pub trait UserKeyStoreInterface {
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
+
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for Store {
+ #[instrument(skip_all)]
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ user_key_store
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for MockDb {
+ #[instrument(skip_all)]
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let mut locked_user_key_store = self.user_key_store.lock().await;
+
+ if locked_user_key_store
+ .iter()
+ .any(|user_key| user_key.user_id == user_key_store.user_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "user_key_store",
+ key: Some(user_key_store.user_id.clone()),
+ })?;
+ }
+
+ let user_key_store = Conversion::convert(user_key_store)
+ .await
+ .change_context(errors::StorageError::MockDbError)?;
+ locked_user_key_store.push(user_key_store.clone());
+
+ user_key_store
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.user_key_store
+ .lock()
+ .await
+ .iter()
+ .find(|user_key_store| user_key_store.user_id == user_id)
+ .cloned()
+ .ok_or(errors::StorageError::ValueNotFound(format!(
+ "No user_key_store is found for user_id={}",
+ user_id
+ )))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 857da69d4b3..cff4fc67db3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1197,7 +1197,8 @@ impl User {
web::resource("/data")
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
- );
+ )
+ .service(web::resource("/totp/begin").route(web::get().to(totp_begin)));
#[cfg(feature = "email")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5f8346a8f23..5bef68073f0 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -210,7 +210,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
- | Flow::UpdateUserAccountDetails => Self::User,
+ | Flow::UpdateUserAccountDetails
+ | Flow::TotpBegin => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index f990438b2f1..db12729d01a 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -612,3 +612,17 @@ pub async fn user_from_email(
))
.await
}
+
+pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::TotpBegin;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::begin_totp(state, user),
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs
index e5f6b8c9660..d18ae0d0190 100644
--- a/crates/router/src/types/domain.rs
+++ b/crates/router/src/types/domain.rs
@@ -9,6 +9,7 @@ pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
pub mod user;
+pub mod user_key_store;
pub use address::*;
pub use customer::*;
@@ -19,3 +20,4 @@ pub use merchant_key_store::*;
pub use payments::*;
#[cfg(feature = "olap")]
pub use user::*;
+pub use user_key_store::*;
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 7e1a1eee3e8..00881626c1c 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -6,7 +6,7 @@ use api_models::{
use common_enums::TokenPurpose;
use common_utils::{errors::CustomResult, pii};
use diesel_models::{
- enums::UserStatus,
+ enums::{TotpStatus, UserStatus},
organization as diesel_org,
organization::Organization,
user as storage_user,
@@ -15,6 +15,7 @@ use diesel_models::{
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
use once_cell::sync::Lazy;
+use rand::distributions::{Alphanumeric, DistString};
use router_env::env;
use unicode_segmentation::UnicodeSegmentation;
@@ -26,7 +27,7 @@ use crate::{
},
db::StorageInterface,
routes::AppState,
- services::{authentication as auth, authentication::UserFromToken, authorization::info},
+ services::{self, authentication as auth, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
utils::{self, user::password},
};
@@ -35,6 +36,8 @@ pub mod dashboard_metadata;
pub mod decision_manager;
pub use decision_manager::*;
+use super::{types as domain_types, UserKeyStore};
+
#[derive(Clone)]
pub struct UserName(Secret<String>);
@@ -863,6 +866,49 @@ impl UserFromStorage {
)
}
}
+
+ pub async fn get_or_create_key_store(&self, state: &AppState) -> UserResult<UserKeyStore> {
+ let master_key = state.store.get_master_key();
+ let key_store_result = state
+ .store
+ .get_user_key_store_by_user_id(self.get_user_id(), &master_key.to_vec().into())
+ .await;
+
+ if let Ok(key_store) = key_store_result {
+ Ok(key_store)
+ } else if key_store_result
+ .as_ref()
+ .map_err(|e| e.current_context().is_db_not_found())
+ .err()
+ .unwrap_or(false)
+ {
+ let key = services::generate_aes256_key()
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Unable to generate aes 256 key")?;
+
+ let key_store = UserKeyStore {
+ user_id: self.get_user_id().to_string(),
+ key: domain_types::encrypt(key.to_vec().into(), master_key)
+ .await
+ .change_context(UserErrors::InternalServerError)?,
+ created_at: common_utils::date_time::now(),
+ };
+ state
+ .store
+ .insert_user_key_store(key_store, &master_key.to_vec().into())
+ .await
+ .change_context(UserErrors::InternalServerError)
+ } else {
+ Err(key_store_result
+ .err()
+ .map(|e| e.change_context(UserErrors::InternalServerError))
+ .unwrap_or(UserErrors::InternalServerError.into()))
+ }
+ }
+
+ pub fn get_totp_status(&self) -> TotpStatus {
+ self.0.totp_status
+ }
}
impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
@@ -1031,3 +1077,36 @@ impl RoleName {
self.0
}
}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct RecoveryCodes(pub Vec<Secret<String>>);
+
+impl RecoveryCodes {
+ pub fn generate_new() -> Self {
+ let mut rand = rand::thread_rng();
+ let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT)
+ .map(|_| {
+ let code_part_1 =
+ Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
+ let code_part_2 =
+ Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
+
+ Secret::new(format!("{}-{}", code_part_1, code_part_2))
+ })
+ .collect::<Vec<_>>();
+
+ Self(recovery_codes)
+ }
+
+ pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> {
+ self.0
+ .iter()
+ .cloned()
+ .map(password::generate_password_hash)
+ .collect::<Result<Vec<_>, _>>()
+ }
+
+ pub fn into_inner(self) -> Vec<Secret<String>> {
+ self.0
+ }
+}
diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs
new file mode 100644
index 00000000000..4c1427d58dc
--- /dev/null
+++ b/crates/router/src/types/domain/user_key_store.rs
@@ -0,0 +1,59 @@
+use common_utils::{
+ crypto::{Encryptable, GcmAes256},
+ date_time,
+};
+use error_stack::ResultExt;
+use masking::{PeekInterface, Secret};
+use time::PrimitiveDateTime;
+
+use crate::{
+ errors::{CustomResult, ValidationError},
+ types::domain::types::TypeEncryption,
+};
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct UserKeyStore {
+ pub user_id: String,
+ pub key: Encryptable<Secret<Vec<u8>>>,
+ pub created_at: PrimitiveDateTime,
+}
+
+#[async_trait::async_trait]
+impl super::behaviour::Conversion for UserKeyStore {
+ type DstType = diesel_models::user_key_store::UserKeyStore;
+ type NewDstType = diesel_models::user_key_store::UserKeyStoreNew;
+
+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
+ Ok(diesel_models::user_key_store::UserKeyStore {
+ key: self.key.into(),
+ user_id: self.user_id,
+ created_at: self.created_at,
+ })
+ }
+
+ async fn convert_back(
+ item: Self::DstType,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Self, ValidationError>
+ where
+ Self: Sized,
+ {
+ Ok(Self {
+ key: Encryptable::decrypt(item.key, key.peek(), GcmAes256)
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?,
+ user_id: item.user_id,
+ created_at: item.created_at,
+ })
+ }
+
+ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
+ Ok(diesel_models::user_key_store::UserKeyStoreNew {
+ user_id: self.user_id,
+ key: self.key.into(),
+ created_at: date_time::now(),
+ })
+ }
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 33e9aa6769c..4980958c9ac 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,12 +1,14 @@
use std::collections::HashMap;
use api_models::user as user_api;
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, pii};
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::ResultExt;
-use masking::Secret;
+use masking::ExposeInterface;
+use totp_rs::{Algorithm, TOTP};
use crate::{
+ consts,
core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
services::{
@@ -74,7 +76,7 @@ pub async fn generate_jwt_auth_token(
state: &AppState,
user: &UserFromStorage,
user_role: &UserRole,
-) -> UserResult<Secret<String>> {
+) -> UserResult<masking::Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
user_role.merchant_id.clone(),
@@ -83,7 +85,7 @@ pub async fn generate_jwt_auth_token(
user_role.org_id.clone(),
)
.await?;
- Ok(Secret::new(token))
+ Ok(masking::Secret::new(token))
}
pub async fn generate_jwt_auth_token_with_custom_role_attributes(
@@ -92,7 +94,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
merchant_id: String,
org_id: String,
role_id: String,
-) -> UserResult<Secret<String>> {
+) -> UserResult<masking::Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
merchant_id,
@@ -101,14 +103,14 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
org_id,
)
.await?;
- Ok(Secret::new(token))
+ Ok(masking::Secret::new(token))
}
pub fn get_dashboard_entry_response(
state: &AppState,
user: UserFromStorage,
user_role: UserRole,
- token: Secret<String>,
+ token: masking::Secret<String>,
) -> UserResult<user_api::DashboardEntryResponse> {
let verification_days_left = get_verification_days_left(state, &user)?;
@@ -185,9 +187,31 @@ pub async fn get_user_from_db_by_email(
.map(UserFromStorage::from)
}
-pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> {
+pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> masking::Secret<String> {
match resp {
user_api::SignInResponse::DashboardEntry(data) => data.token.clone(),
user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
}
}
+
+pub fn generate_default_totp(
+ email: pii::Email,
+ secret: Option<masking::Secret<String>>,
+) -> UserResult<TOTP> {
+ let secret = secret
+ .map(|sec| totp_rs::Secret::Encoded(sec.expose()))
+ .unwrap_or_else(totp_rs::Secret::generate_secret)
+ .to_bytes()
+ .change_context(UserErrors::InternalServerError)?;
+
+ TOTP::new(
+ Algorithm::SHA1,
+ consts::user::TOTP_DIGITS,
+ consts::user::TOTP_TOLERANCE,
+ consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
+ secret,
+ Some(consts::user::TOTP_ISSUER_NAME.to_string()),
+ email.expose().expose(),
+ )
+ .change_context(UserErrors::InternalServerError)
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b360d20fed1..b3252302413 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -396,6 +396,8 @@ pub enum Flow {
UpdateRole,
/// User email flow start
UserFromEmail,
+ /// Begin TOTP
+ TotpBegin,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 3657201f878..0ada6513ff0 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -57,6 +57,7 @@ pub struct MockDb {
pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>,
pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>,
pub roles: Arc<Mutex<Vec<store::role::Role>>>,
+ pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,
}
impl MockDb {
@@ -100,6 +101,7 @@ impl MockDb {
payouts: Default::default(),
authentications: Default::default(),
roles: Default::default(),
+ user_key_store: Default::default(),
})
}
}
diff --git a/migrations/2024-05-06-105026_user_key_store_table/down.sql b/migrations/2024-05-06-105026_user_key_store_table/down.sql
new file mode 100644
index 00000000000..63df9500997
--- /dev/null
+++ b/migrations/2024-05-06-105026_user_key_store_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+DROP TABLE IF EXISTS user_key_store;
diff --git a/migrations/2024-05-06-105026_user_key_store_table/up.sql b/migrations/2024-05-06-105026_user_key_store_table/up.sql
new file mode 100644
index 00000000000..48147e6f597
--- /dev/null
+++ b/migrations/2024-05-06-105026_user_key_store_table/up.sql
@@ -0,0 +1,6 @@
+-- Your SQL goes here
+CREATE TABLE IF NOT EXISTS user_key_store (
+ user_id VARCHAR(64) PRIMARY KEY,
+ key bytea NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT now()
+);
diff --git a/migrations/2024-05-07-080628_user_totp/down.sql b/migrations/2024-05-07-080628_user_totp/down.sql
new file mode 100644
index 00000000000..d8e5840e35c
--- /dev/null
+++ b/migrations/2024-05-07-080628_user_totp/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users DROP COLUMN totp_status;
+ALTER TABLE users DROP COLUMN totp_secret;
+ALTER TABLE users DROP COLUMN totp_recovery_codes;
+
+DROP TYPE "TotpStatus";
diff --git a/migrations/2024-05-07-080628_user_totp/up.sql b/migrations/2024-05-07-080628_user_totp/up.sql
new file mode 100644
index 00000000000..770a3fbd4c5
--- /dev/null
+++ b/migrations/2024-05-07-080628_user_totp/up.sql
@@ -0,0 +1,10 @@
+-- Your SQL goes here
+CREATE TYPE "TotpStatus" AS ENUM (
+ 'set',
+ 'in_progress',
+ 'not_set'
+);
+
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_status "TotpStatus" DEFAULT 'not_set' NOT NULL;
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret bytea DEFAULT NULL;
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_recovery_codes TEXT[] DEFAULT NULL;
|
2024-05-07T17:02:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- This PR adds a new table `user_key_store`, which stores the encryption keys for the user's secrets.
- A new API `begin_totp` has been added, which will check if the user has setup the TOTP or not, and respond with TOTP secret which user has to scan to setup the TOTP in his authenticator application if user didn't setup TOTP.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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 #4575
Closes #4576
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```curl
curl --location 'http://localhost:8080/user/totp/begin' \
--header 'Authorization: Bearer SPT with purpose as totp' \
```
If user hasn't setup TOTP, then the response should be like this:
```json
{
"secret": {
"secret": "EL63X66IYIK2KHIH7DPRYLQTKLUGZMN2",
"totp_url": "otpauth://totp/Hyperswitch:{user_email}?secret=EL63X66IYIK2KHIH7DPRYLQTKLUGZMN2&issuer=Hyperswitch",
"recovery_codes": [
"UNiW-lqXn",
"CpSF-c1TP",
"m2zI-hp4w",
"NGFE-ypVh",
"YxlU-QrNj",
"Nsdu-89FC",
"7OZM-Z4Av",
"LJLD-X80O"
]
}
}
```
If user has completed TOTP setup, then the secret will be null:
```json
{
"secret": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
339da8b0c9a1e388b65ff5d82a162e758c85ec6b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4573
|
Bug: [REFACTOR] remove `Ctx` generic from payments core
Remove the `Ctx` generic being used in payments core as this is not required anymore
|
diff --git a/.typos.toml b/.typos.toml
index 642eaded60e..3223e799cc3 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -36,6 +36,7 @@ ws = "ws" # Web socket
ws2ipdef = "ws2ipdef" # WinSock Extension
ws2tcpip = "ws2tcpip" # WinSock Extension
ZAR = "ZAR" # South African Rand currency code
+JOD = "JOD" # Jordan currency code
[default.extend-words]
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index d67e10a96e5..b8ef4137f9d 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -6,7 +6,7 @@ use router_env::{instrument, tracing, Flow, Tag};
use crate::{
compatibility::{stripe::errors, wrap},
- core::{api_locking::GetLockingInput, payment_methods::Oss, payments},
+ core::{api_locking::GetLockingInput, payments},
logger,
routes::{self, payments::get_or_generate_payment_id},
services::{api, authentication as auth},
@@ -58,7 +58,7 @@ pub async fn payment_intents_create(
create_payment_req,
|state, auth, req, req_state| {
let eligible_connectors = req.connector.clone();
- payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -118,7 +118,7 @@ pub async fn payment_intents_retrieve(
&req,
payload,
|state, auth, payload, req_state| {
- payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>(
+ payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -188,7 +188,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds(
&req,
payload,
|state, auth, req, req_state| {
- payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -197,7 +197,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds(
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
- None,
+ None,
api_types::HeaderPayload::default(),
)
},
@@ -254,7 +254,7 @@ pub async fn payment_intents_update(
payload,
|state, auth, req, req_state| {
let eligible_connectors = req.connector.clone();
- payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -326,7 +326,7 @@ pub async fn payment_intents_confirm(
payload,
|state, auth, req, req_state| {
let eligible_connectors = req.connector.clone();
- payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -387,7 +387,7 @@ pub async fn payment_intents_capture(
&req,
payload,
|state, auth, payload, req_state| {
- payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -396,7 +396,7 @@ pub async fn payment_intents_capture(
payload,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
- None,
+ None,
api_types::HeaderPayload::default(),
)
},
@@ -452,7 +452,7 @@ pub async fn payment_intents_cancel(
&req,
payload,
|state, auth, req, req_state| {
- payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _, Oss>(
+ payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs
index 60627ee5642..c7bde0dbcdd 100644
--- a/crates/router/src/compatibility/stripe/setup_intents.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents.rs
@@ -9,7 +9,7 @@ use crate::{
stripe::{errors, payment_intents::types as stripe_payment_types},
wrap,
},
- core::{api_locking, payment_methods::Oss, payments},
+ core::{api_locking, payments},
routes,
services::{api, authentication as auth},
types::api as api_types,
@@ -58,8 +58,7 @@ pub async fn setup_intents_create(
api_types::PaymentsResponse,
_,
_,
- _,
- Oss,
+ _
>(
state,
req_state,
@@ -120,7 +119,7 @@ pub async fn setup_intents_retrieve(
&req,
payload,
|state, auth, payload, req_state| {
- payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>(
+ payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -191,8 +190,7 @@ pub async fn setup_intents_update(
api_types::PaymentsResponse,
_,
_,
- _,
- Oss,
+ _
>(
state,
req_state,
@@ -265,8 +263,7 @@ pub async fn setup_intents_confirm(
api_types::PaymentsResponse,
_,
_,
- _,
- Oss,
+ _
>(
state,
req_state,
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 22e1074802d..d949a30a011 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -454,7 +454,7 @@ impl<F, T>
}),
),
_ => {
- let redirction_url = data
+ let redirection_url = data
.redirect_url
.as_ref()
.filter(|redirect_str| !redirect_str.is_empty())
@@ -465,7 +465,7 @@ impl<F, T>
})
.transpose()?;
- let redirection_data = redirction_url
+ let redirection_data = redirection_url
.map(|url| services::RedirectForm::from((url, services::Method::Get)));
(
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index e26d5d0b461..4d614662a4d 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -437,7 +437,7 @@ where
}
#[allow(clippy::too_many_arguments)]
-pub async fn pre_payment_frm_core<'a, F, Req, Ctx>(
+pub async fn pre_payment_frm_core<'a, F, Req>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
payment_data: &mut payments::PaymentData<F>,
@@ -447,7 +447,7 @@ pub async fn pre_payment_frm_core<'a, F, Req, Ctx>(
should_continue_transaction: &mut bool,
should_continue_capture: &mut bool,
key_store: domain::MerchantKeyStore,
- operation: &BoxedOperation<'_, F, Req, Ctx>,
+ operation: &BoxedOperation<'_, F, Req>,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
@@ -616,9 +616,9 @@ where
}
#[allow(clippy::too_many_arguments)]
-pub async fn call_frm_before_connector_call<'a, F, Req, Ctx>(
+pub async fn call_frm_before_connector_call<'a, F, Req>(
db: &dyn StorageInterface,
- operation: &BoxedOperation<'_, F, Req, Ctx>,
+ operation: &BoxedOperation<'_, F, Req>,
merchant_account: &domain::MerchantAccount,
payment_data: &mut payments::PaymentData<F>,
state: &AppState,
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index 49862495f3e..758574809c2 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -17,7 +17,6 @@ use crate::{
types::{FrmData, PaymentDetails, PaymentToFrmData, CANCEL_INITIATED},
ConnectorDetailsCore, FrmConfigsObject,
},
- payment_methods::Oss,
payments,
},
db::StorageInterface,
@@ -214,7 +213,6 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost {
_,
_,
_,
- Oss,
>(
state.clone(),
req_state.clone(),
@@ -269,7 +267,6 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost {
_,
_,
_,
- Oss,
>(
state.clone(),
req_state.clone(),
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index b2a4959edfb..71f0bdac03a 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -9,6 +9,7 @@ use api_models::payments::CardToken;
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
use diesel_models::enums;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+use router_env::{instrument, tracing};
use crate::{
core::{errors::RouterResult, payments::helpers, pm_auth as core_pm_auth},
@@ -19,238 +20,214 @@ use crate::{
},
};
-pub struct Oss;
-
-#[async_trait::async_trait]
-pub trait PaymentMethodRetrieve {
- async fn retrieve_payment_method(
- pm_data: &Option<payments::PaymentMethodData>,
- state: &AppState,
- payment_intent: &PaymentIntent,
- payment_attempt: &PaymentAttempt,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)>;
-
- async fn retrieve_payment_method_with_token(
- state: &AppState,
- key_store: &domain::MerchantKeyStore,
- token: &storage::PaymentTokenData,
- payment_intent: &PaymentIntent,
- card_token_data: Option<&CardToken>,
- customer: &Option<domain::Customer>,
- storage_scheme: common_enums::enums::MerchantStorageScheme,
- ) -> RouterResult<storage::PaymentMethodDataWithId>;
-}
-
-#[async_trait::async_trait]
-impl PaymentMethodRetrieve for Oss {
- async fn retrieve_payment_method(
- pm_data: &Option<payments::PaymentMethodData>,
- state: &AppState,
- payment_intent: &PaymentIntent,
- payment_attempt: &PaymentAttempt,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)> {
- match pm_data {
- pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
- state,
- payment_attempt,
- payment_intent,
- enums::PaymentMethod::Card,
- pm,
- merchant_key_store,
- )
- .await?;
-
- Ok((pm_opt.to_owned(), payment_token))
- }
- pm @ Some(api::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
- pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
- state,
- payment_attempt,
- payment_intent,
- enums::PaymentMethod::BankTransfer,
- pm,
- merchant_key_store,
- )
- .await?;
-
- Ok((pm_opt.to_owned(), payment_token))
- }
- pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
- state,
- payment_attempt,
- payment_intent,
- enums::PaymentMethod::Wallet,
- pm,
- merchant_key_store,
- )
- .await?;
-
- Ok((pm_opt.to_owned(), payment_token))
- }
- pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
- state,
- payment_attempt,
- payment_intent,
- enums::PaymentMethod::BankRedirect,
- pm,
- merchant_key_store,
- )
- .await?;
-
- Ok((pm_opt.to_owned(), payment_token))
- }
- _ => Ok((None, None)),
+#[instrument(skip_all)]
+pub async fn retrieve_payment_method(
+ pm_data: &Option<payments::PaymentMethodData>,
+ state: &AppState,
+ payment_intent: &PaymentIntent,
+ payment_attempt: &PaymentAttempt,
+ merchant_key_store: &domain::MerchantKeyStore,
+) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)> {
+ match pm_data {
+ pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::Card,
+ pm,
+ merchant_key_store,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ pm @ Some(api::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
+ pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::BankTransfer,
+ pm,
+ merchant_key_store,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
}
+ pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::Wallet,
+ pm,
+ merchant_key_store,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::BankRedirect,
+ pm,
+ merchant_key_store,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ _ => Ok((None, None)),
}
+}
- async fn retrieve_payment_method_with_token(
- state: &AppState,
- merchant_key_store: &domain::MerchantKeyStore,
- token_data: &storage::PaymentTokenData,
- payment_intent: &PaymentIntent,
- card_token_data: Option<&CardToken>,
- customer: &Option<domain::Customer>,
- storage_scheme: common_enums::enums::MerchantStorageScheme,
- ) -> RouterResult<storage::PaymentMethodDataWithId> {
- let token = match token_data {
- storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
- helpers::retrieve_payment_method_with_temporary_token(
- state,
- &generic_token.token,
- payment_intent,
- merchant_key_store,
- card_token_data,
- )
- .await?
- .map(
- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
- payment_method_data: Some(payment_method_data),
- payment_method: Some(payment_method),
- payment_method_id: None,
- },
- )
- .unwrap_or_default()
- }
+#[instrument(skip_all)]
+pub async fn retrieve_payment_method_with_token(
+ state: &AppState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ token_data: &storage::PaymentTokenData,
+ payment_intent: &PaymentIntent,
+ card_token_data: Option<&CardToken>,
+ customer: &Option<domain::Customer>,
+ storage_scheme: common_enums::enums::MerchantStorageScheme,
+) -> RouterResult<storage::PaymentMethodDataWithId> {
+ let token = match token_data {
+ storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
+ helpers::retrieve_payment_method_with_temporary_token(
+ state,
+ &generic_token.token,
+ payment_intent,
+ merchant_key_store,
+ card_token_data,
+ )
+ .await?
+ .map(
+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
+ payment_method_data: Some(payment_method_data),
+ payment_method: Some(payment_method),
+ payment_method_id: None,
+ },
+ )
+ .unwrap_or_default()
+ }
- storage::PaymentTokenData::Temporary(generic_token) => {
- helpers::retrieve_payment_method_with_temporary_token(
- state,
- &generic_token.token,
- payment_intent,
- merchant_key_store,
- card_token_data,
- )
- .await?
- .map(
- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
- payment_method_data: Some(payment_method_data),
- payment_method: Some(payment_method),
- payment_method_id: None,
- },
- )
- .unwrap_or_default()
- }
+ storage::PaymentTokenData::Temporary(generic_token) => {
+ helpers::retrieve_payment_method_with_temporary_token(
+ state,
+ &generic_token.token,
+ payment_intent,
+ merchant_key_store,
+ card_token_data,
+ )
+ .await?
+ .map(
+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
+ payment_method_data: Some(payment_method_data),
+ payment_method: Some(payment_method),
+ payment_method_id: None,
+ },
+ )
+ .unwrap_or_default()
+ }
- storage::PaymentTokenData::Permanent(card_token) => {
- helpers::retrieve_card_with_permanent_token(
- state,
- card_token.locker_id.as_ref().unwrap_or(&card_token.token),
- card_token
- .payment_method_id
- .as_ref()
- .unwrap_or(&card_token.token),
- payment_intent,
- card_token_data,
- merchant_key_store,
- storage_scheme,
- )
- .await
- .map(|card| Some((card, enums::PaymentMethod::Card)))?
- .map(
- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
- payment_method_data: Some(payment_method_data),
- payment_method: Some(payment_method),
- payment_method_id: Some(
- card_token
- .payment_method_id
- .as_ref()
- .unwrap_or(&card_token.token)
- .to_string(),
- ),
- },
- )
- .unwrap_or_default()
- }
+ storage::PaymentTokenData::Permanent(card_token) => {
+ helpers::retrieve_card_with_permanent_token(
+ state,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token),
+ payment_intent,
+ card_token_data,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .map(|card| Some((card, enums::PaymentMethod::Card)))?
+ .map(
+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
+ payment_method_data: Some(payment_method_data),
+ payment_method: Some(payment_method),
+ payment_method_id: Some(
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token)
+ .to_string(),
+ ),
+ },
+ )
+ .unwrap_or_default()
+ }
- storage::PaymentTokenData::PermanentCard(card_token) => {
- helpers::retrieve_card_with_permanent_token(
- state,
- card_token.locker_id.as_ref().unwrap_or(&card_token.token),
- card_token
- .payment_method_id
- .as_ref()
- .unwrap_or(&card_token.token),
- payment_intent,
- card_token_data,
- merchant_key_store,
- storage_scheme,
- )
- .await
- .map(|card| Some((card, enums::PaymentMethod::Card)))?
- .map(
- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
- payment_method_data: Some(payment_method_data),
- payment_method: Some(payment_method),
- payment_method_id: Some(
- card_token
- .payment_method_id
- .as_ref()
- .unwrap_or(&card_token.token)
- .to_string(),
- ),
- },
- )
- .unwrap_or_default()
- }
+ storage::PaymentTokenData::PermanentCard(card_token) => {
+ helpers::retrieve_card_with_permanent_token(
+ state,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token),
+ payment_intent,
+ card_token_data,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .map(|card| Some((card, enums::PaymentMethod::Card)))?
+ .map(
+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
+ payment_method_data: Some(payment_method_data),
+ payment_method: Some(payment_method),
+ payment_method_id: Some(
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token)
+ .to_string(),
+ ),
+ },
+ )
+ .unwrap_or_default()
+ }
- storage::PaymentTokenData::AuthBankDebit(auth_token) => {
- core_pm_auth::retrieve_payment_method_from_auth_service(
- state,
- merchant_key_store,
- auth_token,
- payment_intent,
- customer,
- )
- .await?
- .map(
- |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
- payment_method_data: Some(payment_method_data),
- payment_method: Some(payment_method),
- payment_method_id: None,
- },
- )
- .unwrap_or_default()
- }
+ storage::PaymentTokenData::AuthBankDebit(auth_token) => {
+ core_pm_auth::retrieve_payment_method_from_auth_service(
+ state,
+ merchant_key_store,
+ auth_token,
+ payment_intent,
+ customer,
+ )
+ .await?
+ .map(
+ |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
+ payment_method_data: Some(payment_method_data),
+ payment_method: Some(payment_method),
+ payment_method_id: None,
+ },
+ )
+ .unwrap_or_default()
+ }
- storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId {
- payment_method: None,
- payment_method_data: None,
- payment_method_id: None,
- },
- };
- Ok(token)
- }
+ storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId {
+ payment_method: None,
+ payment_method_data: None,
+ payment_method_id: None,
+ },
+ };
+ Ok(token)
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0e10c2a5417..239d999bf62 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -69,7 +69,6 @@ use crate::{
core::{
authentication as authentication_core,
errors::{self, CustomResult, RouterResponse, RouterResult},
- payment_methods::PaymentMethodRetrieve,
utils,
},
db::StorageInterface,
@@ -93,7 +92,7 @@ use crate::{
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
-pub async fn payments_operation_core<F, Req, Op, FData, Ctx>(
+pub async fn payments_operation_core<F, Req, Op, FData>(
state: &AppState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
@@ -114,7 +113,7 @@ pub async fn payments_operation_core<F, Req, Op, FData, Ctx>(
where
F: Send + Clone + Sync,
Req: Authenticate + Clone,
- Op: Operation<F, Req, Ctx> + Send + Sync,
+ Op: Operation<F, Req> + Send + Sync,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
@@ -125,11 +124,10 @@ where
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
- PaymentResponse: Operation<F, FData, Ctx>,
+ PaymentResponse: Operation<F, FData>,
FData: Send + Sync + Clone,
- Ctx: PaymentMethodRetrieve,
{
- let operation: BoxedOperation<'_, F, Req, Ctx> = Box::new(operation);
+ let operation: BoxedOperation<'_, F, Req> = Box::new(operation);
tracing::Span::current().record("merchant_id", merchant_account.merchant_id.as_str());
let (operation, validate_result) = operation
@@ -734,7 +732,7 @@ where
}
}
#[allow(clippy::too_many_arguments)]
-pub async fn payments_core<F, Res, Req, Op, FData, Ctx>(
+pub async fn payments_core<F, Res, Req, Op, FData>(
state: AppState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
@@ -749,20 +747,19 @@ pub async fn payments_core<F, Res, Req, Op, FData, Ctx>(
where
F: Send + Clone + Sync,
FData: Send + Sync + Clone,
- Op: Operation<F, Req, Ctx> + Send + Sync + Clone,
+ Op: Operation<F, Req> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
Res: transformers::ToResponse<PaymentData<F>, Op>,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
- Ctx: PaymentMethodRetrieve,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
- PaymentResponse: Operation<F, FData, Ctx>,
+ PaymentResponse: Operation<F, FData>,
{
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
@@ -771,7 +768,7 @@ where
.collect()
});
let (payment_data, _req, customer, connector_http_status_code, external_latency) =
- payments_operation_core::<_, _, _, _, Ctx>(
+ payments_operation_core::<_, _, _, _>(
&state,
req_state,
merchant_account,
@@ -814,7 +811,7 @@ pub struct PaymentsRedirectResponseData {
}
#[async_trait::async_trait]
-pub trait PaymentRedirectFlow<Ctx: PaymentMethodRetrieve>: Sync {
+pub trait PaymentRedirectFlow: Sync {
// Associated type for call_payment_flow response
type PaymentFlowResponse;
@@ -912,7 +909,7 @@ pub trait PaymentRedirectFlow<Ctx: PaymentMethodRetrieve>: Sync {
pub struct PaymentRedirectCompleteAuthorize;
#[async_trait::async_trait]
-impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCompleteAuthorize {
+impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse;
#[allow(clippy::too_many_arguments)]
@@ -944,7 +941,6 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCom
_,
_,
_,
- Ctx,
>(
state.clone(),
req_state,
@@ -1043,7 +1039,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCom
pub struct PaymentRedirectSync;
#[async_trait::async_trait]
-impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectSync {
+impl PaymentRedirectFlow for PaymentRedirectSync {
type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse;
#[allow(clippy::too_many_arguments)]
@@ -1074,14 +1070,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectSyn
expand_attempts: None,
expand_captures: None,
};
- let response = Box::pin(payments_core::<
- api::PSync,
- api::PaymentsResponse,
- _,
- _,
- _,
- Ctx,
- >(
+ let response = Box::pin(payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
state.clone(),
req_state,
merchant_account,
@@ -1141,7 +1130,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectSyn
pub struct PaymentAuthenticateCompleteAuthorize;
#[async_trait::async_trait]
-impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticateCompleteAuthorize {
+impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
type PaymentFlowResponse = router_types::AuthenticatePaymentFlowResponse;
#[allow(clippy::too_many_arguments)]
@@ -1235,7 +1224,6 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticat
_,
_,
_,
- Ctx,
>(
state.clone(),
req_state,
@@ -1266,14 +1254,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticat
expand_attempts: None,
expand_captures: None,
};
- Box::pin(payments_core::<
- api::PSync,
- api::PaymentsResponse,
- _,
- _,
- _,
- Ctx,
- >(
+ Box::pin(payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
state.clone(),
req_state,
merchant_account.clone(),
@@ -1386,13 +1367,13 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticat
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
-pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>(
+pub async fn call_connector_service<F, RouterDReq, ApiRequest>(
state: &AppState,
req_state: ReqState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector: api::ConnectorData,
- operation: &BoxedOperation<'_, F, ApiRequest, Ctx>,
+ operation: &BoxedOperation<'_, F, ApiRequest>,
payment_data: &mut PaymentData<F>,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
@@ -1409,8 +1390,6 @@ where
PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>:
Feature<F, RouterDReq> + Send,
- Ctx: PaymentMethodRetrieve,
-
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
@@ -1611,15 +1590,14 @@ where
router_data_res
}
-async fn blocklist_guard<F, ApiRequest, Ctx>(
+async fn blocklist_guard<F, ApiRequest>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
- operation: &BoxedOperation<'_, F, ApiRequest, Ctx>,
+ operation: &BoxedOperation<'_, F, ApiRequest>,
payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse>
where
F: Send + Clone + Sync,
- Ctx: PaymentMethodRetrieve,
{
let merchant_id = &payment_data.payment_attempt.merchant_id;
let blocklist_enabled_key = format!("guard_blocklist_for_{merchant_id}");
@@ -1651,7 +1629,7 @@ where
}
#[allow(clippy::too_many_arguments)]
-pub async fn call_multiple_connectors_service<F, Op, Req, Ctx>(
+pub async fn call_multiple_connectors_service<F, Op, Req>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
@@ -1672,10 +1650,9 @@ where
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
- Ctx: PaymentMethodRetrieve,
// To perform router related operation for PaymentResponse
- PaymentResponse: Operation<F, Req, Ctx>,
+ PaymentResponse: Operation<F, Req>,
{
let call_connectors_start_time = Instant::now();
let mut join_handlers = Vec::with_capacity(connectors.len());
@@ -1869,12 +1846,12 @@ where
}
}
-async fn complete_preprocessing_steps_if_required<F, Req, Q, Ctx>(
+async fn complete_preprocessing_steps_if_required<F, Req, Q>(
state: &AppState,
connector: &api::ConnectorData,
payment_data: &PaymentData<F>,
mut router_data: router_types::RouterData<F, Req, router_types::PaymentsResponseData>,
- operation: &BoxedOperation<'_, F, Q, Ctx>,
+ operation: &BoxedOperation<'_, F, Q>,
should_continue_payment: bool,
) -> RouterResult<(
router_types::RouterData<F, Req, router_types::PaymentsResponseData>,
@@ -2234,9 +2211,9 @@ pub enum TokenizationAction {
}
#[allow(clippy::too_many_arguments)]
-pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, Ctx>(
+pub async fn get_connector_tokenization_action_when_confirm_true<F, Req>(
state: &AppState,
- operation: &BoxedOperation<'_, F, Req, Ctx>,
+ operation: &BoxedOperation<'_, F, Req>,
payment_data: &mut PaymentData<F>,
validate_result: &operations::ValidateResult<'_>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
@@ -2245,7 +2222,6 @@ pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, Ctx>(
) -> RouterResult<(PaymentData<F>, TokenizationAction)>
where
F: Send + Clone,
- Ctx: PaymentMethodRetrieve,
{
let connector = payment_data.payment_attempt.connector.to_owned();
@@ -2359,9 +2335,9 @@ where
Ok(payment_data_and_tokenization_action)
}
-pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, Ctx>(
+pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req>(
state: &AppState,
- operation: &BoxedOperation<'_, F, Req, Ctx>,
+ operation: &BoxedOperation<'_, F, Req>,
payment_data: &mut PaymentData<F>,
validate_result: &operations::ValidateResult<'_>,
merchant_key_store: &domain::MerchantKeyStore,
@@ -2369,7 +2345,6 @@ pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F,
) -> RouterResult<PaymentData<F>>
where
F: Send + Clone,
- Ctx: PaymentMethodRetrieve,
{
// On confirm is false and only router related
let is_external_authentication_requested = payment_data
@@ -2607,16 +2582,15 @@ impl CustomerDetailsExt for CustomerDetails {
}
}
-pub fn if_not_create_change_operation<'a, Op, F, Ctx>(
+pub fn if_not_create_change_operation<'a, Op, F>(
status: storage_enums::IntentStatus,
confirm: Option<bool>,
current: &'a Op,
-) -> BoxedOperation<'_, F, api::PaymentsRequest, Ctx>
+) -> BoxedOperation<'_, F, api::PaymentsRequest>
where
F: Send + Clone,
- Op: Operation<F, api::PaymentsRequest, Ctx> + Send + Sync,
- &'a Op: Operation<F, api::PaymentsRequest, Ctx>,
- Ctx: PaymentMethodRetrieve,
+ Op: Operation<F, api::PaymentsRequest> + Send + Sync,
+ &'a Op: Operation<F, api::PaymentsRequest>,
{
if confirm.unwrap_or(false) {
Box::new(PaymentConfirm)
@@ -2630,16 +2604,15 @@ where
}
}
-pub fn is_confirm<'a, F: Clone + Send, R, Op, Ctx>(
+pub fn is_confirm<'a, F: Clone + Send, R, Op>(
operation: &'a Op,
confirm: Option<bool>,
-) -> BoxedOperation<'_, F, R, Ctx>
+) -> BoxedOperation<'_, F, R>
where
- PaymentConfirm: Operation<F, R, Ctx>,
- &'a PaymentConfirm: Operation<F, R, Ctx>,
- Op: Operation<F, R, Ctx> + Send + Sync,
- &'a Op: Operation<F, R, Ctx>,
- Ctx: PaymentMethodRetrieve,
+ PaymentConfirm: Operation<F, R>,
+ &'a PaymentConfirm: Operation<F, R>,
+ Op: Operation<F, R> + Send + Sync,
+ &'a Op: Operation<F, R>,
{
if confirm.unwrap_or(false) {
Box::new(&PaymentConfirm)
@@ -3023,8 +2996,8 @@ where
}
#[allow(clippy::too_many_arguments)]
-pub async fn get_connector_choice<F, Req, Ctx>(
- operation: &BoxedOperation<'_, F, Req, Ctx>,
+pub async fn get_connector_choice<F, Req>(
+ operation: &BoxedOperation<'_, F, Req>,
state: &AppState,
req: &Req,
merchant_account: &domain::MerchantAccount,
@@ -3036,7 +3009,6 @@ pub async fn get_connector_choice<F, Req, Ctx>(
) -> RouterResult<Option<ConnectorCallType>>
where
F: Send + Clone,
- Ctx: PaymentMethodRetrieve,
{
let connector_choice = operation
.to_domain()?
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index e4c4540cacf..dd5f7279ecc 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -39,12 +39,12 @@ use crate::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
- payment_methods::{cards, vault, PaymentMethodRetrieve},
+ payment_methods::{self, cards, vault},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
- routes::{metrics, payment_methods, AppState},
+ routes::{metrics, payment_methods as payment_methods_handler, AppState},
services,
types::{
self as core_types,
@@ -1234,11 +1234,10 @@ where
}
}
-pub fn response_operation<'a, F, R, Ctx>() -> BoxedOperation<'a, F, R, Ctx>
+pub fn response_operation<'a, F, R>() -> BoxedOperation<'a, F, R>
where
F: Send + Clone,
- Ctx: PaymentMethodRetrieve,
- PaymentResponse: Operation<F, R, Ctx>,
+ PaymentResponse: Operation<F, R>,
{
Box::new(PaymentResponse)
}
@@ -1468,15 +1467,15 @@ pub async fn get_connector_default(
#[instrument(skip_all)]
#[allow(clippy::type_complexity)]
-pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
- operation: BoxedOperation<'a, F, R, Ctx>,
+pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
+ operation: BoxedOperation<'a, F, R>,
db: &dyn StorageInterface,
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
-) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError> {
+) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError> {
let request_customer_details = req
.get_required_value("customer")
.change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?;
@@ -1884,15 +1883,15 @@ pub async fn retrieve_payment_token_data(
Ok(token_data)
}
-pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
- operation: BoxedOperation<'a, F, R, Ctx>,
+pub async fn make_pm_data<'a, F: Clone, R>(
+ operation: BoxedOperation<'a, F, R>,
state: &'a AppState,
payment_data: &mut PaymentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, R, Ctx>,
+ BoxedOperation<'a, F, R>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -1935,7 +1934,7 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
// TODO: Handle case where payment method and token both are present in request properly.
let (payment_method, pm_id) = match (request, payment_data.token_data.as_ref()) {
(_, Some(hyperswitch_token)) => {
- let pm_data = Ctx::retrieve_payment_method_with_token(
+ let pm_data = payment_methods::retrieve_payment_method_with_token(
state,
merchant_key_store,
hyperswitch_token,
@@ -1963,7 +1962,7 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
}
(Some(_), _) => {
- let (payment_method_data, payment_token) = Ctx::retrieve_payment_method(
+ let (payment_method_data, payment_token) = payment_methods::retrieve_payment_method(
request,
state,
&payment_data.payment_intent,
@@ -2001,7 +2000,7 @@ pub async fn store_in_vault_and_generate_ppmt(
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let key_for_hyperswitch_token = payment_attempt.payment_method.map(|payment_method| {
- payment_methods::ParentPaymentMethodToken::create_key_for_token((
+ payment_methods_handler::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method,
))
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index da9a2108691..35fc2897ea4 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -27,10 +27,7 @@ pub use self::{
};
use super::{helpers, CustomerDetails, PaymentData};
use crate::{
- core::{
- errors::{self, CustomResult, RouterResult},
- payment_methods::PaymentMethodRetrieve,
- },
+ core::errors::{self, CustomResult, RouterResult},
db::StorageInterface,
routes::{app::ReqState, AppState},
services,
@@ -43,26 +40,26 @@ use crate::{
},
};
-pub type BoxedOperation<'a, F, T, Ctx> = Box<dyn Operation<F, T, Ctx> + Send + Sync + 'a>;
+pub type BoxedOperation<'a, F, T> = Box<dyn Operation<F, T> + Send + Sync + 'a>;
-pub trait Operation<F: Clone, T, Ctx: PaymentMethodRetrieve>: Send + std::fmt::Debug {
- fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, T, Ctx> + Send + Sync)> {
+pub trait Operation<F: Clone, T>: Send + std::fmt::Debug {
+ fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("validate request interface not found for {self:?}"))
}
fn to_get_tracker(
&self,
- ) -> RouterResult<&(dyn GetTracker<F, PaymentData<F>, T, Ctx> + Send + Sync)> {
+ ) -> RouterResult<&(dyn GetTracker<F, PaymentData<F>, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
- fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Ctx>> {
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, T>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
fn to_update_tracker(
&self,
- ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, T, Ctx> + Send + Sync)> {
+ ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("update tracker interface not found for {self:?}"))
}
@@ -84,16 +81,16 @@ pub struct ValidateResult<'a> {
}
#[allow(clippy::type_complexity)]
-pub trait ValidateRequest<F, R, Ctx: PaymentMethodRetrieve> {
+pub trait ValidateRequest<F, R> {
fn validate_request<'a, 'b>(
&'b self,
request: &R,
merchant_account: &'a domain::MerchantAccount,
- ) -> RouterResult<(BoxedOperation<'b, F, R, Ctx>, ValidateResult<'a>)>;
+ ) -> RouterResult<(BoxedOperation<'b, F, R>, ValidateResult<'a>)>;
}
-pub struct GetTrackerResponse<'a, F: Clone, R, Ctx> {
- pub operation: BoxedOperation<'a, F, R, Ctx>,
+pub struct GetTrackerResponse<'a, F: Clone, R> {
+ pub operation: BoxedOperation<'a, F, R>,
pub customer_details: Option<CustomerDetails>,
pub payment_data: PaymentData<F>,
pub business_profile: storage::business_profile::BusinessProfile,
@@ -101,7 +98,7 @@ pub struct GetTrackerResponse<'a, F: Clone, R, Ctx> {
}
#[async_trait]
-pub trait GetTracker<F: Clone, D, R, Ctx: PaymentMethodRetrieve>: Send {
+pub trait GetTracker<F: Clone, D, R>: Send {
#[allow(clippy::too_many_arguments)]
async fn get_trackers<'a>(
&'a self,
@@ -112,11 +109,11 @@ pub trait GetTracker<F: Clone, D, R, Ctx: PaymentMethodRetrieve>: Send {
mechant_key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
payment_confirm_source: Option<enums::PaymentSource>,
- ) -> RouterResult<GetTrackerResponse<'a, F, R, Ctx>>;
+ ) -> RouterResult<GetTrackerResponse<'a, F, R>>;
}
#[async_trait]
-pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
+pub trait Domain<F: Clone, R>: Send + Sync {
/// This will fetch customer details, (this operation is flow specific)
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -125,7 +122,7 @@ pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError>;
+ ) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn make_pm_data<'a>(
@@ -136,7 +133,7 @@ pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, R, Ctx>,
+ BoxedOperation<'a, F, R>,
Option<api::PaymentMethodData>,
Option<String>,
)>;
@@ -204,7 +201,7 @@ pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
#[async_trait]
#[allow(clippy::too_many_arguments)]
-pub trait UpdateTracker<F, D, Req, Ctx: PaymentMethodRetrieve>: Send {
+pub trait UpdateTracker<F, D, Req>: Send {
async fn update_trackers<'b>(
&'b self,
db: &'b AppState,
@@ -216,7 +213,7 @@ pub trait UpdateTracker<F, D, Req, Ctx: PaymentMethodRetrieve>: Send {
mechant_key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, Req, Ctx>, D)>
+ ) -> RouterResult<(BoxedOperation<'b, F, Req>, D)>
where
F: 'b + Send;
}
@@ -251,13 +248,10 @@ pub trait PostUpdateTracker<F, D, R: Send>: Send {
}
#[async_trait]
-impl<
- F: Clone + Send,
- Ctx: PaymentMethodRetrieve,
- Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Ctx>,
- > Domain<F, api::PaymentsRetrieveRequest, Ctx> for Op
+impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest>>
+ Domain<F, api::PaymentsRetrieveRequest> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -269,7 +263,7 @@ where
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -308,7 +302,7 @@ where
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -335,13 +329,10 @@ where
}
#[async_trait]
-impl<
- F: Clone + Send,
- Ctx: PaymentMethodRetrieve,
- Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Ctx>,
- > Domain<F, api::PaymentsCaptureRequest, Ctx> for Op
+impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest>>
+ Domain<F, api::PaymentsCaptureRequest> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -353,7 +344,7 @@ where
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -380,7 +371,7 @@ where
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -410,13 +401,10 @@ where
}
#[async_trait]
-impl<
- F: Clone + Send,
- Ctx: PaymentMethodRetrieve,
- Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Ctx>,
- > Domain<F, api::PaymentsCancelRequest, Ctx> for Op
+impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest>>
+ Domain<F, api::PaymentsCancelRequest> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -428,7 +416,7 @@ where
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsCancelRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -456,7 +444,7 @@ where
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsCancelRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -486,13 +474,10 @@ where
}
#[async_trait]
-impl<
- F: Clone + Send,
- Ctx: PaymentMethodRetrieve,
- Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Ctx>,
- > Domain<F, api::PaymentsRejectRequest, Ctx> for Op
+impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest>>
+ Domain<F, api::PaymentsRejectRequest> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -504,7 +489,7 @@ where
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRejectRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -521,7 +506,7 @@ where
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRejectRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 8dffd8eaec3..bd7e22547f3 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -10,7 +10,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, PaymentData},
},
routes::{app::ReqState, AppState},
@@ -29,8 +28,8 @@ use crate::{
pub struct PaymentApprove;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentApprove
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
+ for PaymentApprove
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -42,7 +41,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest>> {
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
@@ -191,9 +190,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentApprove
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for PaymentApprove {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -207,7 +204,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
PaymentData<F>,
)>
where
@@ -247,16 +244,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- ValidateRequest<F, api::PaymentsCaptureRequest, Ctx> for PaymentApprove
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for PaymentApprove {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCaptureRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
operations::ValidateResult<'a>,
)> {
let request_merchant_id = request.merchant_id.as_deref();
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 32035391fb7..3aa3fb4254b 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -11,7 +11,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
@@ -31,9 +30,7 @@ use crate::{
pub struct PaymentCancel;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest, Ctx> for PaymentCancel
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for PaymentCancel {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -44,7 +41,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest>> {
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
@@ -206,9 +203,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest, Ctx> for PaymentCancel
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for PaymentCancel {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -222,7 +217,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCancelRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsCancelRequest>,
PaymentData<F>,
)>
where
@@ -276,16 +271,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- ValidateRequest<F, api::PaymentsCancelRequest, Ctx> for PaymentCancel
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCancelRequest> for PaymentCancel {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCancelRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsCancelRequest>,
operations::ValidateResult<'a>,
)> {
Ok((
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index d4c3f0acad7..b22cedb16ee 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -10,7 +10,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, types::MultipleCaptureData},
},
routes::{app::ReqState, AppState},
@@ -29,8 +28,8 @@ use crate::{
pub struct PaymentCapture;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentCapture
+impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
+ for PaymentCapture
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -42,7 +41,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest>> {
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
@@ -247,8 +246,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest, Ctx>
+impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
for PaymentCapture
{
#[instrument(skip_all)]
@@ -264,7 +262,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
payments::PaymentData<F>,
)>
where
@@ -298,16 +296,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- ValidateRequest<F, api::PaymentsCaptureRequest, Ctx> for PaymentCapture
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for PaymentCapture {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCaptureRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
operations::ValidateResult<'a>,
)> {
Ok((
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 d31ec14a723..9d8fb0def73 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -11,7 +11,6 @@ use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
- payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
@@ -31,9 +30,7 @@ use crate::{
pub struct CompleteAuthorize;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for CompleteAuthorize
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -44,7 +41,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
@@ -331,9 +328,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
- for CompleteAuthorize
-{
+impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -344,7 +339,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -370,7 +365,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -422,9 +417,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for CompleteAuthorize
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -437,10 +430,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
- PaymentData<F>,
- )>
+ ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
{
@@ -448,16 +438,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
- for CompleteAuthorize
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAuthorize {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsRequest>,
operations::ValidateResult<'a>,
)> {
let payment_id = request
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 3d4f2a3cad8..fe023d0f382 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -17,7 +17,6 @@ use crate::{
blocklist::utils as blocklist_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
- payment_methods::PaymentMethodRetrieve,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
PaymentData,
@@ -40,9 +39,7 @@ use crate::{
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentConfirm;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentConfirm
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -53,7 +50,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
let (currency, amount);
@@ -651,9 +648,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
- for PaymentConfirm
-{
+impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -664,7 +659,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -690,7 +685,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -927,9 +922,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentConfirm
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -942,10 +935,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: api::HeaderPayload,
- ) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
- PaymentData<F>,
- )>
+ ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
{
@@ -1245,16 +1235,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
- for PaymentConfirm
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsRequest>,
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0d241202208..10193284850 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -23,7 +23,6 @@ use crate::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_link,
- payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
@@ -48,9 +47,7 @@ pub struct PaymentCreate;
/// The `get_trackers` function for `PaymentsCreate` is an entrypoint for new payments
/// This will create all the entities required for a new payment from the request
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentCreate
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -61,7 +58,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
merchant_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
let db = &*state.store;
let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_account).await;
let merchant_id = &merchant_account.merchant_id;
@@ -362,7 +359,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.await
.transpose()?;
- let operation = payments::if_not_create_change_operation::<_, F, Ctx>(
+ let operation = payments::if_not_create_change_operation::<_, F>(
payment_intent.status,
request.confirm,
self,
@@ -466,9 +463,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
- for PaymentCreate
-{
+impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -479,7 +474,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -505,7 +500,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -554,9 +549,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentCreate
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -569,10 +562,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
- PaymentData<F>,
- )>
+ ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
{
@@ -659,16 +649,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
- for PaymentCreate
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsRequest>,
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 8845fe836e2..d301de8f78c 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -10,7 +10,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, PaymentAddress, PaymentData},
},
routes::{app::ReqState, AppState},
@@ -28,9 +27,7 @@ use crate::{
pub struct PaymentReject;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, PaymentsCancelRequest, Ctx> for PaymentReject
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -41,7 +38,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest>> {
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
@@ -190,9 +187,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest, Ctx> for PaymentReject
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -205,10 +200,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_mechant_key_store: &domain::MerchantKeyStore,
_should_decline_transaction: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(
- BoxedOperation<'b, F, PaymentsCancelRequest, Ctx>,
- PaymentData<F>,
- )>
+ ) -> RouterResult<(BoxedOperation<'b, F, PaymentsCancelRequest>, PaymentData<F>)>
where
F: 'b + Send,
{
@@ -258,16 +250,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsCancelRequest, Ctx>
- for PaymentReject
-{
+impl<F: Send + Clone> ValidateRequest<F, PaymentsCancelRequest> for PaymentReject {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsCancelRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, PaymentsCancelRequest, Ctx>,
+ BoxedOperation<'b, F, PaymentsCancelRequest>,
operations::ValidateResult<'a>,
)> {
Ok((
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index c3ef748c037..1f39742ec53 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -16,8 +16,7 @@ use crate::{
connector::utils::PaymentResponseRouterData,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- mandate,
- payment_methods::{self, PaymentMethodRetrieve},
+ mandate, payment_methods,
payments::{
helpers::{
self as payments_helpers,
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 808eb20eb12..a002be72eaa 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -11,7 +11,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, PaymentData},
},
db::StorageInterface,
@@ -30,8 +29,8 @@ use crate::{
pub struct PaymentSession;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest, Ctx> for PaymentSession
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
+ for PaymentSession
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -43,7 +42,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest>> {
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -215,9 +214,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest, Ctx> for PaymentSession
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -231,7 +228,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsSessionRequest>,
PaymentData<F>,
)>
where
@@ -258,16 +255,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- ValidateRequest<F, api::PaymentsSessionRequest, Ctx> for PaymentSession
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for PaymentSession {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsSessionRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsSessionRequest>,
operations::ValidateResult<'a>,
)> {
//paymentid is already generated and should be sent in the request
@@ -286,13 +281,10 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<
- F: Clone + Send,
- Ctx: PaymentMethodRetrieve,
- Op: Send + Sync + Operation<F, api::PaymentsSessionRequest, Ctx>,
- > Domain<F, api::PaymentsSessionRequest, Ctx> for Op
+impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsSessionRequest>>
+ Domain<F, api::PaymentsSessionRequest> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -304,7 +296,7 @@ where
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsSessionRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsSessionRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -330,7 +322,7 @@ where
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsSessionRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index c7042908b63..ec48abf491f 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -10,7 +10,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
@@ -29,9 +28,7 @@ use crate::{
pub struct PaymentStart;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsStartRequest, Ctx> for PaymentStart
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -42,7 +39,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest>> {
let (mut payment_intent, payment_attempt, currency, amount);
let db = &*state.store;
@@ -202,9 +199,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest, Ctx> for PaymentStart
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -218,7 +213,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsStartRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsStartRequest>,
PaymentData<F>,
)>
where
@@ -228,16 +223,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsStartRequest, Ctx>
- for PaymentStart
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentStart {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsStartRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsStartRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsStartRequest>,
operations::ValidateResult<'a>,
)> {
let request_merchant_id = Some(&request.merchant_id[..]);
@@ -262,13 +255,10 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
}
#[async_trait]
-impl<
- F: Clone + Send,
- Ctx: PaymentMethodRetrieve,
- Op: Send + Sync + Operation<F, api::PaymentsStartRequest, Ctx>,
- > Domain<F, api::PaymentsStartRequest, Ctx> for Op
+impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsStartRequest>>
+ Domain<F, api::PaymentsStartRequest> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsStartRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::PaymentsStartRequest>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -280,7 +270,7 @@ where
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsStartRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -306,7 +296,7 @@ where
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsStartRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 06ad57346f5..046e34fc40b 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -11,7 +11,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{
helpers, operations, types as payment_types, CustomerDetails, PaymentAddress,
PaymentData,
@@ -31,39 +30,31 @@ use crate::{
#[operation(operations = "all", flow = "sync")]
pub struct PaymentStatus;
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> Operation<F, api::PaymentsRequest, Ctx>
- for PaymentStatus
-{
- fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, Ctx>> {
+impl<F: Send + Clone> Operation<F, api::PaymentsRequest> for PaymentStatus {
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest>> {
Ok(self)
}
fn to_update_tracker(
&self,
- ) -> RouterResult<
- &(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> + Send + Sync),
- > {
+ ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)>
+ {
Ok(self)
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> Operation<F, api::PaymentsRequest, Ctx>
- for &PaymentStatus
-{
- fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, Ctx>> {
+impl<F: Send + Clone> Operation<F, api::PaymentsRequest> for &PaymentStatus {
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest>> {
Ok(*self)
}
fn to_update_tracker(
&self,
- ) -> RouterResult<
- &(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> + Send + Sync),
- > {
+ ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)>
+ {
Ok(*self)
}
}
#[async_trait]
-impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
- for PaymentStatus
-{
+impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -74,7 +65,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -100,7 +91,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -149,9 +140,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentStatus
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus {
async fn update_trackers<'b>(
&'b self,
_state: &'b AppState,
@@ -163,10 +152,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
- PaymentData<F>,
- )>
+ ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
{
@@ -175,9 +161,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus {
async fn update_trackers<'b>(
&'b self,
_state: &'b AppState,
@@ -190,7 +174,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRetrieveRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
PaymentData<F>,
)>
where
@@ -201,8 +185,8 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest>
+ for PaymentStatus
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -214,8 +198,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, Ctx>>
- {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest>> {
get_tracker_for_sync(
payment_id,
merchant_account,
@@ -232,8 +215,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
- Ctx: PaymentMethodRetrieve,
- Op: Operation<F, api::PaymentsRetrieveRequest, Ctx> + 'a + Send + Sync,
+ Op: Operation<F, api::PaymentsRetrieveRequest> + 'a + Send + Sync,
>(
payment_id: &api::PaymentIdType,
merchant_account: &domain::MerchantAccount,
@@ -242,7 +224,7 @@ async fn get_tracker_for_sync<
request: &api::PaymentsRetrieveRequest,
operation: Op,
storage_scheme: enums::MerchantStorageScheme,
-) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, Ctx>> {
+) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest>> {
let (payment_intent, mut payment_attempt, currency, amount);
(payment_intent, payment_attempt) = get_payment_intent_payment_attempt(
@@ -504,15 +486,13 @@ async fn get_tracker_for_sync<
Ok(get_trackers_response)
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- ValidateRequest<F, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for PaymentStatus {
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRetrieveRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRetrieveRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
operations::ValidateResult<'a>,
)> {
let request_merchant_id = request.merchant_id.as_deref();
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index de83b935ff0..b3e6dcb7b9b 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -14,7 +14,6 @@ use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
- payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
@@ -34,9 +33,7 @@ use crate::{
pub struct PaymentUpdate;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentUpdate
-{
+impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -47,7 +44,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
let (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency);
let payment_id = payment_id
@@ -327,7 +324,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
})
.await
.transpose()?;
- let (next_operation, amount): (BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, _) =
+ let (next_operation, amount): (BoxedOperation<'a, F, api::PaymentsRequest>, _) =
if request.confirm.unwrap_or(false) {
let amount = {
let amount = request
@@ -469,9 +466,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
- for PaymentUpdate
-{
+impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -482,7 +477,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -508,7 +503,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'a, F, api::PaymentsRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
@@ -557,9 +552,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentUpdate
-{
+impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -572,10 +565,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
- PaymentData<F>,
- )>
+ ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
{
@@ -734,16 +724,14 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
- for PaymentUpdate
-{
+impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate {
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ BoxedOperation<'b, F, api::PaymentsRequest>,
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index ddba82fc04d..a80de40bb26 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -11,7 +11,6 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{
self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails,
PaymentAddress,
@@ -35,8 +34,8 @@ use crate::{
pub struct PaymentIncrementalAuthorization;
#[async_trait]
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest, Ctx>
+impl<F: Send + Clone>
+ GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
@@ -49,9 +48,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_payment_confirm_source: Option<common_enums::PaymentSource>,
- ) -> RouterResult<
- operations::GetTrackerResponse<'a, F, PaymentsIncrementalAuthorizationRequest, Ctx>,
- > {
+ ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsIncrementalAuthorizationRequest>>
+ {
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
@@ -171,8 +169,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone, Ctx: PaymentMethodRetrieve>
- UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest, Ctx>
+impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
@@ -188,7 +185,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, Ctx>,
+ BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest>,
payments::PaymentData<F>,
)>
where
@@ -262,8 +259,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
}
}
-impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
- ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, Ctx>
+impl<F: Send + Clone> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
@@ -272,7 +268,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
request: &PaymentsIncrementalAuthorizationRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, Ctx>,
+ BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest>,
operations::ValidateResult<'a>,
)> {
Ok((
@@ -288,8 +284,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
#[async_trait]
-impl<F: Clone + Send, Ctx: PaymentMethodRetrieve>
- Domain<F, PaymentsIncrementalAuthorizationRequest, Ctx> for PaymentIncrementalAuthorization
+impl<F: Clone + Send> Domain<F, PaymentsIncrementalAuthorizationRequest>
+ for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -301,7 +297,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve>
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
- BoxedOperation<'a, F, PaymentsIncrementalAuthorizationRequest, Ctx>,
+ BoxedOperation<'a, F, PaymentsIncrementalAuthorizationRequest>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -318,7 +314,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve>
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
) -> RouterResult<(
- BoxedOperation<'a, F, PaymentsIncrementalAuthorizationRequest, Ctx>,
+ BoxedOperation<'a, F, PaymentsIncrementalAuthorizationRequest>,
Option<api::PaymentMethodData>,
Option<String>,
)> {
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 58c58ffaef8..1a39c06fb04 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -11,7 +11,6 @@ use router_env::{
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payment_methods::PaymentMethodRetrieve,
payments::{
self,
flows::{ConstructFlowSpecificData, Feature},
@@ -31,7 +30,7 @@ use crate::{
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
-pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>(
+pub async fn do_gsm_actions<F, ApiRequest, FData>(
state: &app::AppState,
req_state: ReqState,
payment_data: &mut payments::PaymentData<F>,
@@ -40,7 +39,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>(
mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
- operation: &operations::BoxedOperation<'_, F, ApiRequest, Ctx>,
+ operation: &operations::BoxedOperation<'_, F, ApiRequest>,
customer: &Option<domain::Customer>,
validate_result: &operations::ValidateResult<'_>,
schedule_time: Option<time::PrimitiveDateTime>,
@@ -49,12 +48,11 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>(
where
F: Clone + Send + Sync,
FData: Send + Sync,
- payments::PaymentResponse: operations::Operation<F, FData, Ctx>,
+ payments::PaymentResponse: operations::Operation<F, FData>,
payments::PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
- Ctx: PaymentMethodRetrieve,
{
let mut retries = None;
@@ -267,11 +265,11 @@ fn get_flow_name<F>() -> RouterResult<String> {
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
-pub async fn do_retry<F, ApiRequest, FData, Ctx>(
+pub async fn do_retry<F, ApiRequest, FData>(
state: &routes::AppState,
req_state: ReqState,
connector: api::ConnectorData,
- operation: &operations::BoxedOperation<'_, F, ApiRequest, Ctx>,
+ operation: &operations::BoxedOperation<'_, F, ApiRequest>,
customer: &Option<domain::Customer>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
@@ -285,12 +283,11 @@ pub async fn do_retry<F, ApiRequest, FData, Ctx>(
where
F: Clone + Send + Sync,
FData: Send + Sync,
- payments::PaymentResponse: operations::Operation<F, FData, Ctx>,
+ payments::PaymentResponse: operations::Operation<F, FData>,
payments::PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
- Ctx: PaymentMethodRetrieve,
{
metrics::AUTO_RETRY_PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]);
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 3c04fdb7e49..37393f0aab1 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -30,7 +30,6 @@ use crate::{
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse},
- payment_methods::PaymentMethodRetrieve,
payments, refunds,
},
db::StorageInterface,
@@ -59,7 +58,7 @@ use crate::{
const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5;
const MERCHANT_ID: &str = "merchant_id";
-pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>(
+pub async fn payments_incoming_webhook_flow(
state: AppState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
@@ -102,7 +101,6 @@ pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>(
_,
_,
_,
- Ctx,
>(
state.clone(),
req_state,
@@ -419,7 +417,7 @@ pub async fn get_or_update_dispute_object(
}
#[allow(clippy::too_many_arguments)]
-pub async fn external_authentication_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>(
+pub async fn external_authentication_incoming_webhook_flow(
state: AppState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
@@ -511,7 +509,6 @@ pub async fn external_authentication_incoming_webhook_flow<Ctx: PaymentMethodRet
_,
_,
_,
- Ctx,
>(
state.clone(),
req_state,
@@ -752,7 +749,7 @@ pub async fn disputes_incoming_webhook_flow(
}
}
-async fn bank_transfer_webhook_flow<Ctx: PaymentMethodRetrieve>(
+async fn bank_transfer_webhook_flow(
state: AppState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
@@ -782,7 +779,6 @@ async fn bank_transfer_webhook_flow<Ctx: PaymentMethodRetrieve>(
_,
_,
_,
- Ctx,
>(
state.clone(),
req_state,
@@ -1448,7 +1444,7 @@ fn raise_webhooks_analytics_event(
}
#[allow(clippy::too_many_arguments)]
-pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>(
+pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>(
flow: &impl router_env::types::FlowMetric,
state: AppState,
req_state: ReqState,
@@ -1460,7 +1456,7 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodR
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let (application_response, webhooks_response_tracker, serialized_req) =
- Box::pin(webhooks_core::<W, Ctx>(
+ Box::pin(webhooks_core::<W>(
state.clone(),
req_state,
req,
@@ -1513,7 +1509,7 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodR
}
#[instrument(skip_all)]
-pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>(
+pub async fn webhooks_core<W: types::OutgoingWebhookType>(
state: AppState,
req_state: ReqState,
req: &actix_web::HttpRequest,
@@ -1750,7 +1746,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr
})?;
match flow_type {
- api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow::<Ctx>(
+ api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
state.clone(),
req_state,
merchant_account,
@@ -1789,7 +1785,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr
.await
.attach_printable("Incoming webhook flow for disputes failed")?,
- api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow::<Ctx>(
+ api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(
state.clone(),
req_state,
merchant_account,
@@ -1816,7 +1812,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr
.attach_printable("Incoming webhook flow for mandates failed")?,
api::WebhookFlow::ExternalAuthentication => {
- Box::pin(external_authentication_incoming_webhook_flow::<Ctx>(
+ Box::pin(external_authentication_incoming_webhook_flow(
state.clone(),
req_state,
merchant_account,
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 70112e27037..6a1b424a330 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -14,7 +14,6 @@ use crate::{
self as app,
core::{
errors::{self, http_not_implemented},
- payment_methods::{Oss, PaymentMethodRetrieve},
payments::{self, PaymentRedirectFlow},
utils as core_utils,
},
@@ -125,7 +124,7 @@ pub async fn payments_create(
&req,
payload,
|state, auth, req, req_state| {
- authorize_verify_select::<_, Oss>(
+ authorize_verify_select::<_>(
payments::PaymentCreate,
state,
req_state,
@@ -195,7 +194,7 @@ pub async fn payments_start(
_,
_,
_,
- Oss,
+
>(
state,
req_state,
@@ -271,7 +270,7 @@ pub async fn payments_retrieve(
&req,
payload,
|state, auth, req, req_state| {
- payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -344,7 +343,7 @@ pub async fn payments_retrieve_with_gateway_creds(
&req,
payload,
|state, auth, req, req_state| {
- payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -414,7 +413,7 @@ pub async fn payments_update(
&req,
payload,
|state, auth, req, req_state| {
- authorize_verify_select::<_, Oss>(
+ authorize_verify_select::<_>(
payments::PaymentUpdate,
state,
req_state,
@@ -492,7 +491,7 @@ pub async fn payments_confirm(
&req,
payload,
|state, auth, req, req_state| {
- authorize_verify_select::<_, Oss>(
+ authorize_verify_select::<_>(
payments::PaymentConfirm,
state,
req_state,
@@ -551,14 +550,7 @@ pub async fn payments_capture(
&req,
payload,
|state, auth, payload, req_state| {
- payments::payments_core::<
- api_types::Capture,
- payment_types::PaymentsResponse,
- _,
- _,
- _,
- Oss,
- >(
+ payments::payments_core::<api_types::Capture, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -616,7 +608,6 @@ pub async fn payments_connector_session(
_,
_,
_,
- Oss,
>(
state,
req_state,
@@ -682,7 +673,7 @@ pub async fn payments_redirect_response(
&req,
payload,
|state, auth, req, req_state| {
- <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
@@ -743,7 +734,7 @@ pub async fn payments_redirect_response_with_creds_identifier(
&req,
payload,
|state, auth, req, req_state| {
- <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ <payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
@@ -787,7 +778,7 @@ pub async fn payments_complete_authorize(
payload,
|state, auth, req, req_state| {
- <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectCompleteAuthorize {},
state,
req_state,
@@ -841,7 +832,7 @@ pub async fn payments_cancel(
&req,
payload,
|state, auth, req, req_state| {
- payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _,Oss>(
+ payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -999,14 +990,7 @@ pub async fn payments_approve(
&http_req,
payload.clone(),
|state, auth, req, req_state| {
- payments::payments_core::<
- api_types::Capture,
- payment_types::PaymentsResponse,
- _,
- _,
- _,
- Oss,
- >(
+ payments::payments_core::<api_types::Capture, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -1060,14 +1044,7 @@ pub async fn payments_reject(
&http_req,
payload.clone(),
|state, auth, req, req_state| {
- payments::payments_core::<
- api_types::Void,
- payment_types::PaymentsResponse,
- _,
- _,
- _,
- Oss,
- >(
+ payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _>(
state,
req_state,
auth.merchant_account,
@@ -1098,7 +1075,7 @@ pub async fn payments_reject(
}
#[allow(clippy::too_many_arguments)]
-async fn authorize_verify_select<Op, Ctx>(
+async fn authorize_verify_select<Op>(
operation: Op,
state: app::AppState,
req_state: ReqState,
@@ -1109,18 +1086,13 @@ async fn authorize_verify_select<Op, Ctx>(
auth_flow: api::AuthFlow,
) -> errors::RouterResponse<api_models::payments::PaymentsResponse>
where
- Ctx: PaymentMethodRetrieve,
Op: Sync
+ Clone
+ std::fmt::Debug
+ + payments::operations::Operation<api_types::Authorize, api_models::payments::PaymentsRequest>
+ payments::operations::Operation<
- api_types::Authorize,
- api_models::payments::PaymentsRequest,
- Ctx,
- > + payments::operations::Operation<
api_types::SetupMandate,
api_models::payments::PaymentsRequest,
- Ctx,
>,
{
// TODO: Change for making it possible for the flow to be inferred internally or through validation layer
@@ -1133,28 +1105,25 @@ where
match req.payment_type.unwrap_or_default() {
api_models::enums::PaymentType::Normal
| api_models::enums::PaymentType::RecurringMandate
- | api_models::enums::PaymentType::NewMandate => {
- payments::payments_core::<
- api_types::Authorize,
- payment_types::PaymentsResponse,
- _,
- _,
- _,
- Ctx,
- >(
- state,
- req_state,
- merchant_account,
- key_store,
- operation,
- req,
- auth_flow,
- payments::CallConnectorAction::Trigger,
- eligible_connectors,
- header_payload,
- )
- .await
- }
+ | api_models::enums::PaymentType::NewMandate => payments::payments_core::<
+ api_types::Authorize,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ >(
+ state,
+ req_state,
+ merchant_account,
+ key_store,
+ operation,
+ req,
+ auth_flow,
+ payments::CallConnectorAction::Trigger,
+ eligible_connectors,
+ header_payload,
+ )
+ .await,
api_models::enums::PaymentType::SetupMandate => {
payments::payments_core::<
api_types::SetupMandate,
@@ -1162,7 +1131,6 @@ where
_,
_,
_,
- Ctx,
>(
state,
req_state,
@@ -1225,7 +1193,6 @@ pub async fn payments_incremental_authorization(
_,
_,
_,
- Oss,
>(
state,
req_state,
@@ -1342,7 +1309,7 @@ pub async fn post_3ds_payments_authorize(
&req,
payload,
|state, auth, req, req_state| {
- <payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ <payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentAuthenticateCompleteAuthorize {},
state,
req_state,
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index cdf680548a1..fee38dbacd2 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -5,7 +5,6 @@ use super::app::AppState;
use crate::{
core::{
api_locking,
- payment_methods::Oss,
webhooks::{self, types},
},
services::{api, authentication as auth},
@@ -27,7 +26,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
&req,
(),
|state, auth, _, req_state| {
- webhooks::webhooks_wrapper::<W, Oss>(
+ webhooks::webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index 760993decb4..726cbf9de09 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -329,7 +329,6 @@ async fn get_outgoing_webhook_content_and_event_type(
core::{
disputes::retrieve_dispute,
mandate::get_mandate,
- payment_methods::Oss,
payments::{payments_core, CallConnectorAction, PaymentStatus},
refunds::refund_retrieve_core,
},
@@ -351,7 +350,7 @@ async fn get_outgoing_webhook_content_and_event_type(
};
let payments_response =
- match Box::pin(payments_core::<PSync, PaymentsResponse, _, _, _, Oss>(
+ match Box::pin(payments_core::<PSync, PaymentsResponse, _, _, _>(
state,
req_state,
merchant_account,
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index 5dbfff8342e..b7fde1d900e 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -10,7 +10,6 @@ use crate::{
consts,
core::{
errors::StorageErrorExt,
- payment_methods::Oss,
payments::{self as payment_flows, operations},
},
db::StorageInterface,
@@ -60,14 +59,8 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow {
.await?;
// TODO: Add support for ReqState in PT flows
- let (mut payment_data, _, customer, _, _) =
- Box::pin(payment_flows::payments_operation_core::<
- api::PSync,
- _,
- _,
- _,
- Oss,
- >(
+ let (mut payment_data, _, customer, _, _) = Box::pin(
+ payment_flows::payments_operation_core::<api::PSync, _, _, _>(
state,
state.get_req_state(),
merchant_account.clone(),
@@ -78,8 +71,9 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow {
services::AuthFlow::Client,
None,
api::HeaderPayload::default(),
- ))
- .await?;
+ ),
+ )
+ .await?;
let terminal_status = [
enums::AttemptStatus::RouterDeclined,
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index f4325d01b90..45d3b29d66a 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -4,7 +4,7 @@ mod utils;
use router::{
configs,
- core::{payment_methods::Oss, payments},
+ core::payments,
db::StorageImpl,
routes, services,
types::{
@@ -371,7 +371,6 @@ async fn payments_create_core() {
_,
_,
_,
- Oss,
>(
state.clone(),
state.get_req_state(),
@@ -554,7 +553,6 @@ async fn payments_create_core_adyen_no_redirect() {
_,
_,
_,
- Oss,
>(
state.clone(),
state.get_req_state(),
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 56ab453a0f5..278ee80a92a 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -3,7 +3,7 @@
mod utils;
use router::{
- core::{payment_methods::Oss, payments},
+ core::payments,
db::StorageImpl,
types::api::{self, enums as api_enums},
*,
@@ -131,7 +131,6 @@ async fn payments_create_core() {
_,
_,
_,
- Oss,
>(
state.clone(),
state.get_req_state(),
@@ -322,7 +321,6 @@ async fn payments_create_core_adyen_no_redirect() {
_,
_,
_,
- Oss,
>(
state.clone(),
state.get_req_state(),
diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs
index e743a2d9cc5..c1e8c4e5bbc 100644
--- a/crates/router_derive/src/macros/operation.rs
+++ b/crates/router_derive/src/macros/operation.rs
@@ -40,7 +40,7 @@ impl Derives {
let req_type = Conversion::get_req_type(self);
quote! {
#[automatically_derived]
- impl<F:Send+Clone,Ctx: PaymentMethodRetrieve,> Operation<F,#req_type,Ctx> for #struct_name {
+ impl<F:Send+Clone> Operation<F,#req_type> for #struct_name {
#(#fns)*
}
}
@@ -54,7 +54,7 @@ impl Derives {
let req_type = Conversion::get_req_type(self);
quote! {
#[automatically_derived]
- impl<F:Send+Clone,Ctx: PaymentMethodRetrieve,> Operation<F,#req_type,Ctx> for &#struct_name {
+ impl<F:Send+Clone> Operation<F,#req_type> for &#struct_name {
#(#ref_fns)*
}
}
@@ -110,22 +110,22 @@ impl Conversion {
let req_type = Self::get_req_type(ident);
match self {
Self::ValidateRequest => quote! {
- fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type,Ctx> + Send + Sync)> {
+ fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> {
Ok(self)
}
},
Self::GetTracker => quote! {
- fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
+ fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(self)
}
},
Self::Domain => quote! {
- fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type,Ctx>> {
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type>> {
Ok(self)
}
},
Self::UpdateTracker => quote! {
- fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
+ fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(self)
}
},
@@ -158,22 +158,22 @@ impl Conversion {
let req_type = Self::get_req_type(ident);
match self {
Self::ValidateRequest => quote! {
- fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type,Ctx> + Send + Sync)> {
+ fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> {
Ok(*self)
}
},
Self::GetTracker => quote! {
- fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
+ fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(*self)
}
},
Self::Domain => quote! {
- fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type,Ctx>)> {
+ fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type>)> {
Ok(*self)
}
},
Self::UpdateTracker => quote! {
- fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
+ fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(*self)
}
},
|
2024-05-07T15:41:05Z
|
## 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 `Ctx` generic being used in payments core as this is not required anymore.
This PR also fixes the failing typos CI check
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
As this PR just removes the `Ctx` generic, basic sanity testing should suffice
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
59e79ff205dfc2fded993b7a9130b9953bdd07e2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4556
|
Bug: feat: Create new versions of BE pre-login APIs
Currently we've made SPT and decision starter APIs. Now we have to integrate SPT into email specific, signin and signup APIs.
For backwards compatibility, old version should also need to be kept. So we can do these new APIs accessible with a query param.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 14676656d0f..b29b28f0136 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -14,8 +14,8 @@ use crate::user::{
CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
- SendVerifyEmailRequest, SignInResponse, SignInWithTokenResponse, SignUpRequest,
- SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenResponse,
+ SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
+ SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
};
@@ -38,6 +38,12 @@ impl ApiEventMetric for VerifyTokenResponse {
}
}
+impl<T> ApiEventMetric for TokenOrPayloadResponse<T> {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Miscellaneous)
+ }
+}
+
common_utils::impl_misc_api_event_type!(
SignUpRequest,
SignUpWithMerchantIdRequest,
@@ -62,7 +68,6 @@ common_utils::impl_misc_api_event_type!(
SignInResponse,
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
- SignInWithTokenResponse,
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse,
TokenResponse,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index a6d5cf36358..fe4e37f8a8c 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -227,9 +227,9 @@ pub struct TokenResponse {
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
-pub enum SignInWithTokenResponse {
+pub enum TokenOrPayloadResponse<T> {
Token(TokenResponse),
- SignInResponse(SignInResponse),
+ Payload(T),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 25c1c5ecd40..08d63d9097f 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -99,6 +99,7 @@ pub enum UserStatus {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AcceptInvitationRequest {
pub merchant_ids: Vec<String>,
+ // TODO: Remove this once the token only api is being used
pub need_dashboard_entry_response: Option<bool>,
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 58a6452c9bb..6ad0afa9104 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -94,7 +94,7 @@ pub async fn get_user_details(
pub async fn signup(
state: AppState,
request: user_api::SignUpRequest,
-) -> UserResponse<user_api::SignUpResponse> {
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignUpResponse>> {
let new_user = domain::NewUser::try_from(request)?;
new_user
.get_new_merchant()
@@ -117,13 +117,48 @@ pub async fn signup(
let response =
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
+ auth::cookies::set_cookie_response(user_api::TokenOrPayloadResponse::Payload(response), token)
+}
+
+pub async fn signup_token_only_flow(
+ state: AppState,
+ request: user_api::SignUpRequest,
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignUpResponse>> {
+ let new_user = domain::NewUser::try_from(request)?;
+ new_user
+ .get_new_merchant()
+ .get_new_organization()
+ .insert_org_in_db(state.clone())
+ .await?;
+ let user_from_db = new_user
+ .insert_user_and_merchant_in_db(state.clone())
+ .await?;
+ let user_role = new_user
+ .insert_user_role_in_db(
+ state.clone(),
+ consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ UserStatus::Active,
+ )
+ .await?;
+
+ let next_flow =
+ domain::NextFlow::from_origin(domain::Origin::SignUp, user_from_db.clone(), &state).await?;
+
+ let token = next_flow
+ .get_token_with_user_role(&state, &user_role)
+ .await?;
+
+ let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ });
auth::cookies::set_cookie_response(response, token)
}
pub async fn signin(
state: AppState,
request: user_api::SignInRequest,
-) -> UserResponse<user_api::SignInWithTokenResponse> {
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
let user_from_db: domain::UserFromStorage = state
.store
.find_user_by_email(&request.email)
@@ -161,16 +196,13 @@ pub async fn signin(
let response = signin_strategy.get_signin_response(&state).await?;
let token = utils::user::get_token_from_signin_response(&response);
- auth::cookies::set_cookie_response(
- user_api::SignInWithTokenResponse::SignInResponse(response),
- token,
- )
+ auth::cookies::set_cookie_response(user_api::TokenOrPayloadResponse::Payload(response), token)
}
pub async fn signin_token_only_flow(
state: AppState,
request: user_api::SignInRequest,
-) -> UserResponse<user_api::SignInWithTokenResponse> {
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
let user_from_db: domain::UserFromStorage = state
.store
.find_user_by_email(&request.email)
@@ -185,7 +217,7 @@ pub async fn signin_token_only_flow(
let token = next_flow.get_token(&state).await?;
- let response = user_api::SignInWithTokenResponse::Token(user_api::TokenResponse {
+ let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
});
@@ -820,6 +852,73 @@ pub async fn accept_invite_from_email(
auth::cookies::set_cookie_response(response, token)
}
+#[cfg(feature = "email")]
+pub async fn accept_invite_from_email_token_only_flow(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ request: user_api::AcceptInviteFromEmailRequest,
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
+ let token = request.token.expose();
+
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
+ .await
+ .change_context(UserErrors::LinkInvalid)?;
+
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_email(
+ &email_token
+ .get_email()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if user_from_db.get_user_id() != user_token.user_id {
+ return Err(UserErrors::LinkInvalid.into());
+ }
+
+ let merchant_id = email_token
+ .get_merchant_id()
+ .ok_or(UserErrors::LinkInvalid)?;
+
+ let user_role = state
+ .store
+ .update_user_role_by_user_id_merchant_id(
+ user_from_db.get_user_id(),
+ merchant_id,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_from_db.get_user_id().to_string(),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+
+ let current_flow = domain::CurrentFlow::new(
+ user_token.origin,
+ domain::SPTFlow::AcceptInvitationFromEmail.into(),
+ )?;
+ let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
+
+ let token = next_flow
+ .get_token_with_user_role(&state, &user_role)
+ .await?;
+
+ let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ });
+ auth::cookies::set_cookie_response(response, token)
+}
+
pub async fn create_internal_user(
state: AppState,
request: user_api::CreateInternalUserRequest,
@@ -1196,6 +1295,60 @@ pub async fn verify_email(
auth::cookies::set_cookie_response(response, token)
}
+#[cfg(feature = "email")]
+pub async fn verify_email_token_only_flow(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_api::VerifyEmailRequest,
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::SignInResponse>> {
+ let token = req.token.clone().expose();
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
+ .await
+ .change_context(UserErrors::LinkInvalid)?;
+
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+
+ let user_from_email = state
+ .store
+ .find_user_by_email(
+ &email_token
+ .get_email()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ if user_from_email.user_id != user_token.user_id {
+ return Err(UserErrors::LinkInvalid.into());
+ }
+
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .update_user_by_user_id(
+ user_from_email.user_id.as_str(),
+ storage_user::UserUpdate::VerifyUser,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+
+ let current_flow =
+ domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?;
+ let next_flow = current_flow.next(user_from_db, &state).await?;
+ let token = next_flow.get_token(&state).await?;
+
+ let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ });
+
+ auth::cookies::set_cookie_response(response, token)
+}
+
#[cfg(feature = "email")]
pub async fn send_verification_mail(
state: AppState,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 3f913b88a3f..ae20ec51ad4 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -172,8 +172,7 @@ pub async fn accept_invitation(
state: AppState,
user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::AcceptInvitationRequest,
- _req_state: ReqState,
-) -> UserResponse<user_api::DashboardEntryResponse> {
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
state
.store
@@ -215,12 +214,65 @@ pub async fn accept_invitation(
user_role,
token.clone(),
)?;
- return auth::cookies::set_cookie_response(response, token);
+ return auth::cookies::set_cookie_response(
+ user_api::TokenOrPayloadResponse::Payload(response),
+ token,
+ );
}
Ok(ApplicationResponse::StatusOk)
}
+pub async fn accept_invitation_token_only_flow(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_role_api::AcceptInvitationRequest,
+) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
+ let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
+ state
+ .store
+ .update_user_role_by_user_id_merchant_id(
+ user_token.user_id.as_str(),
+ merchant_id,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_token.user_id.clone(),
+ },
+ )
+ .await
+ .map_err(|e| {
+ logger::error!("Error while accepting invitation {}", e);
+ })
+ .ok()
+ }))
+ .await
+ .into_iter()
+ .reduce(Option::or)
+ .flatten()
+ .ok_or(UserErrors::MerchantIdNotFound)?;
+
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(user_token.user_id.as_str())
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ let current_flow =
+ domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::MerchantSelect.into())?;
+ let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
+
+ let token = next_flow
+ .get_token_with_user_role(&state, &user_role)
+ .await?;
+
+ let response = user_api::TokenOrPayloadResponse::Token(user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ });
+ auth::cookies::set_cookie_response(response, token)
+}
+
pub async fn delete_user_role(
state: AppState,
user_from_token: auth::UserFromToken,
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index ede6edbceb8..a3f18168501 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -57,15 +57,23 @@ pub async fn user_signup(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignUpRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignUp;
let req_payload = json_payload.into_inner();
+ let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
- |state, _, req_body, _| user_core::signup(state, req_body),
+ |state, _, req_body, _| async move {
+ if let Some(true) = is_token_only {
+ user_core::signup_token_only_flow(state, req_body).await
+ } else {
+ user_core::signup(state, req_body).await
+ }
+ },
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
@@ -428,18 +436,37 @@ pub async fn accept_invite_from_email(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::AcceptInviteFromEmailRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::AcceptInviteFromEmail;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- |state, _, request_payload, _| user_core::accept_invite_from_email(state, request_payload),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
+ let is_token_only = query.into_inner().token_only;
+ if let Some(true) = is_token_only {
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &req,
+ payload.into_inner(),
+ |state, user, req_payload, _| {
+ user_core::accept_invite_from_email_token_only_flow(state, user, req_payload)
+ },
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::AcceptInvitationFromEmail),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ } else {
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload.into_inner(),
+ |state, _, request_payload, _| {
+ user_core::accept_invite_from_email(state, request_payload)
+ },
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
#[cfg(feature = "email")]
@@ -447,18 +474,35 @@ pub async fn verify_email(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::VerifyEmailRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::VerifyEmail;
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- json_payload.into_inner(),
- |state, _, req_payload, _| user_core::verify_email(state, req_payload),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
+ let is_token_only = query.into_inner().token_only;
+ if let Some(true) = is_token_only {
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &http_req,
+ json_payload.into_inner(),
+ |state, user, req_payload, _| {
+ user_core::verify_email_token_only_flow(state, user, req_payload)
+ },
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::VerifyEmail),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ } else {
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &http_req,
+ json_payload.into_inner(),
+ |state, _, req_payload, _| user_core::verify_email(state, req_payload),
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
#[cfg(feature = "email")]
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 59c07b79855..d406783cc71 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,5 +1,8 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use api_models::user_role::{self as user_role_api, role as role_api};
+use api_models::{
+ user as user_api,
+ user_role::{self as user_role_api, role as role_api},
+};
use common_enums::TokenPurpose;
use router_env::Flow;
@@ -206,15 +209,23 @@ pub async fn accept_invitation(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::AcceptInvitationRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::AcceptInvitation;
let payload = json_payload.into_inner();
+ let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
- user_role_core::accept_invitation,
+ |state, user, req_body, _| async move {
+ if let Some(true) = is_token_only {
+ user_role_core::accept_invitation_token_only_flow(state, user, req_body).await
+ } else {
+ user_role_core::accept_invitation(state, user, req_body).await
+ }
+ },
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index e460bc74649..616c595b244 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -7,6 +7,7 @@ use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResult},
routes::AppState,
services::authentication as auth,
+ utils,
};
#[derive(Eq, PartialEq, Clone, Copy)]
@@ -150,8 +151,9 @@ const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
-const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 4] = [
+const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::JWTFlow(JWTFlow::UserInfo),
@@ -234,16 +236,38 @@ impl NextFlow {
{
self.user.get_verification_days_left(state)?;
}
-
let user_role = self
.user
.get_preferred_or_active_user_role_from_db(state)
.await
.to_not_found_response(UserErrors::InternalServerError)?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role)
+ .await;
+
jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
+
+ pub async fn get_token_with_user_role(
+ &self,
+ state: &AppState,
+ user_role: &UserRole,
+ ) -> UserResult<Secret<String>> {
+ match self.next_flow {
+ UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
+ UserFlow::JWTFlow(jwt_flow) => {
+ #[cfg(feature = "email")]
+ {
+ self.user.get_verification_days_left(state)?;
+ }
+ utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role)
+ .await;
+
+ jwt_flow.generate_jwt(state, self, user_role).await
+ }
+ }
+ }
}
impl From<UserFlow> for TokenPurpose {
@@ -274,3 +298,15 @@ impl From<JWTFlow> for TokenPurpose {
}
}
}
+
+impl From<SPTFlow> for UserFlow {
+ fn from(value: SPTFlow) -> Self {
+ Self::SPTFlow(value)
+ }
+}
+
+impl From<JWTFlow> for UserFlow {
+ fn from(value: JWTFlow) -> Self {
+ Self::JWTFlow(value)
+ }
+}
|
2024-05-06T10:14: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 -->
This PR will add new core functions for the following APIs which can be used with SPTs.
1. Accept Invite
2. Sign up
3. Verify Email
4. Accept Invite from Email
### 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 #4556.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/signup?token_only=true' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "user email",
"password": "password"
}'
```
```
curl --location 'http://localhost:8080/user/accept_invite_from_email?token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as "accept_invite_from_email"' \
--data '{
"token": "email token"
}'
```
```
curl --location 'http://localhost:8080/user/v2/verify_email?token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as "verify_email"' \
--data '{
"token": "email token"
}'
```
```
curl --location 'http://localhost:8080/user/user/invite/accept?token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as "accept_invite"' \
--data '{
"merchant_ids": [
"merchant_1705414503",
"merchant_1705414514"
],
"need_dashboard_entry_response": true
}'
```
All API should respond like this
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDYxNjE1YjAtZjI5Yi00NWIyLWJmNmItODczNTYyYWU1ODhlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJtYWdpY19saW5rIiwiZXhwIjoxNzE0ODExOTAwfQ.CDErXJ89a1o3ROyAKvm6TFW1drHDnlcqg43OoBQjY6A",
"token_type": "totp"
}
```
`token_type` can be
1. `totp`
2. `verify_email`
3. `accept_invite_from_email`
4. `accept_invite`
5. `reset_password`
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
df2c2ca22dc4cea986cbbf30850311d3e85000c5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4538
|
Bug: [BUG] [BAMBORA] Amount not being passed in Decimal format
### Bug Description
For connector Bambora, the amount is not being passed in decimal format for Authorize, Capture and Refund requests.
### Expected Behavior
For connector Bambora, the amount should be passed in decimal format for Authorize, Capture and Refund requests.
### Actual Behavior
For connector Bambora, the amount is not being passed in decimal format for Authorize, Capture and Refund requests.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index 0717b997bad..7ff352416cd 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -62,6 +62,10 @@ impl ConnectorCommon for Bambora {
"bambora"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -187,7 +191,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
"{}/v1/payments/{}{}",
self.base_url(connectors),
connector_payment_id,
- "/completions"
+ "/void"
))
}
@@ -196,7 +200,22 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraPaymentsRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request
+ .currency
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "Currency",
+ })?,
+ req.request
+ .amount
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "Amount",
+ })?,
+ req,
+ ))?;
+
+ let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -376,7 +395,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraPaymentsCaptureRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+
+ let connector_req =
+ bambora::BamboraPaymentsCaptureRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -470,7 +497,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraPaymentsRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+
+ let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -569,7 +603,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraRefundRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req = bambora::BamboraRefundRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 3115f04f483..dbb655c6ca0 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -5,13 +5,46 @@ use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
- connector::utils::{BrowserInformationData, PaymentsAuthorizeRequestData, RouterData},
+ connector::utils::{
+ AddressDetailsData, BrowserInformationData, CardData as OtherCardData,
+ PaymentsAuthorizeRequestData, RouterData,
+ },
consts,
core::errors,
services,
types::{self, api, domain, storage::enums},
};
+pub struct BamboraRouterData<T> {
+ pub amount: f64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for BamboraRouterData<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 = crate::connector::utils::get_amount_as_f64(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraCard {
name: Secret<String>,
@@ -46,16 +79,21 @@ pub struct BamboraBrowserInfo {
javascript_enabled: bool,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Default, Debug, Serialize)]
pub struct BamboraPaymentsRequest {
order_number: String,
- amount: i64,
+ amount: f64,
payment_method: PaymentMethod,
customer_ip: Option<Secret<String, IpAddress>>,
term_url: Option<String>,
card: BamboraCard,
}
+#[derive(Default, Debug, Serialize)]
+pub struct BamboraVoidRequest {
+ amount: f64,
+}
+
fn get_browser_info(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> {
@@ -102,41 +140,41 @@ impl TryFrom<&types::CompleteAuthorizeData> for BamboraThreedsContinueRequest {
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
+impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for BamboraPaymentsRequest {
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: BamboraRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
domain::PaymentMethodData::Card(req_card) => {
- let three_ds = match item.auth_type {
+ let three_ds = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => Some(ThreeDSecure {
enabled: true,
- browser: get_browser_info(item)?,
+ browser: get_browser_info(item.router_data)?,
version: Some(2),
auth_required: Some(true),
}),
enums::AuthenticationType::NoThreeDs => None,
};
let bambora_card = BamboraCard {
- name: item
- .get_optional_billing_full_name()
- .unwrap_or(Secret::new("".to_string())),
+ name: item.router_data.get_billing_address()?.get_full_name()?,
+ expiry_year: req_card.get_card_expiry_year_2_digit()?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
cvd: req_card.card_cvc,
three_d_secure: three_ds,
- complete: item.request.is_auto_capture()?,
+ complete: item.router_data.request.is_auto_capture()?,
};
- let browser_info = item.request.get_browser_info()?;
+ let browser_info = item.router_data.request.get_browser_info()?;
Ok(Self {
- order_number: item.connector_request_reference_id.clone(),
- amount: item.request.amount,
+ order_number: item.router_data.connector_request_reference_id.clone(),
+ amount: item.amount,
payment_method: PaymentMethod::Card,
card: bambora_card,
customer_ip: browser_info
.ip_address
.map(|ip_address| Secret::new(format!("{ip_address}"))),
- term_url: item.request.complete_authorize_url.clone(),
+ term_url: item.router_data.request.complete_authorize_url.clone(),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
@@ -144,12 +182,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
}
}
-impl TryFrom<&types::PaymentsCancelRouterData> for BamboraPaymentsRequest {
+impl TryFrom<BamboraRouterData<&types::PaymentsCancelRouterData>> for BamboraVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: BamboraRouterData<&types::PaymentsCancelRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: 0,
- ..Default::default()
+ amount: item.amount,
})
}
}
@@ -417,15 +456,19 @@ pub enum PaymentMethod {
// Capture
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
pub struct BamboraPaymentsCaptureRequest {
- amount: Option<i64>,
+ amount: Option<f64>,
payment_method: PaymentMethod,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for BamboraPaymentsCaptureRequest {
+impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
+ for BamboraPaymentsCaptureRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: BamboraRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: Some(item.request.amount_to_capture),
+ amount: Some(item.amount),
payment_method: PaymentMethod::Card,
})
}
@@ -433,16 +476,18 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for BamboraPaymentsCaptureReques
// REFUND :
// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Default, Debug, Serialize)]
pub struct BamboraRefundRequest {
- amount: i64,
+ amount: f64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for BamboraRefundRequest {
+impl<F> TryFrom<BamboraRouterData<&types::RefundsRouterData<F>>> for BamboraRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: BamboraRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.request.refund_amount,
+ amount: item.amount,
})
}
}
|
2024-05-03T10:28:04Z
|
## 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 the following changes for connector Bambora:
- Only 2 digit i.e. `25` for `2025` card expiry year will be allowed be pass in Bambora Payments Request.
- Amount will be passed in decimal format for Authorize, Capture and Refund requests.
- Fix Void Flow.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4534
https://github.com/juspay/hyperswitch/issues/4538
## How did you test 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 (Manual):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"capture_method": "manual",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
```
Response:
```
{
"payment_id": "pay_LKthlJrz33C1pr55C7ib",
"merchant_id": "merchant_1714730521",
"status": "requires_capture",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 2500,
"amount_received": null,
"connector": "bambora",
"client_secret": "pay_LKthlJrz33C1pr55C7ib_secret_BaVLQyDPAxLkJFEXfCXD",
"created": "2024-05-03T11:30:29.586Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": "40300000",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1714735829,
"expires": 1714739429,
"secret": "epk_74a8cad9f3c64a229b4236f6999b8c67"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004723",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_LKthlJrz33C1pr55C7ib_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-03T11:45:29.586Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-03T11:30:31.543Z"
}
```
- Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_Bnr8RRNohtyOwlEvTOjg/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response:
```
{
"payment_id": "pay_Bnr8RRNohtyOwlEvTOjg",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": 2500,
"connector": "bambora",
"client_secret": "pay_Bnr8RRNohtyOwlEvTOjg_secret_F7JoawvBWk3zzTJ9o3a8",
"created": "2024-05-03T11:27:21.382Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": "40300000",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "10004714",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_Bnr8RRNohtyOwlEvTOjg_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-03T11:42:21.382Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-03T11:27:32.674Z"
}
```
- Payments (Automatic Capture):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
```
Response:
```
{
"payment_id": "pay_7KsO7eanoa25U0NUwGMy",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": 2500,
"connector": "bambora",
"client_secret": "pay_7KsO7eanoa25U0NUwGMy_secret_MIVHZVOHOByIuQyxzs8H",
"created": "2024-05-03T11:36:55.259Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": "40300000",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1714736215,
"expires": 1714739815,
"secret": "epk_ec99b66693a14bf180eba0f525c07cd0"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004725",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_7KsO7eanoa25U0NUwGMy_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-03T11:51:55.258Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-03T11:36:57.592Z"
}
```
- Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_id": "pay_Bf0CmzVjSJCBVt5e6n3m",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_ksDchUYhgBlvAYz2maZ2",
"payment_id": "pay_Bf0CmzVjSJCBVt5e6n3m",
"amount": 2500,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-05-03T11:38:14.960Z",
"updated_at": "2024-05-03T11:38:14.960Z",
"connector": "bambora",
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
17b369cfabc42d4d06f65b92e967057dba348731
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4532
|
Bug: feat: Create a decision starter API for email flows
As we have split the API flows, there is no API to trigger the email specific flows like Verify email, Accept invite from email, etc...
For this API to work correctly, email token should have the information about the origin.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 594b60b5816..14676656d0f 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -15,8 +15,8 @@ use crate::user::{
GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
SendVerifyEmailRequest, SignInResponse, SignInWithTokenResponse, SignUpRequest,
- SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest,
- UserMerchantCreate, VerifyEmailRequest,
+ SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenResponse,
+ UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -64,7 +64,9 @@ common_utils::impl_misc_api_event_type!(
GetUserDetailsResponse,
SignInWithTokenResponse,
GetUserRoleDetailsRequest,
- GetUserRoleDetailsResponse
+ GetUserRoleDetailsResponse,
+ TokenResponse,
+ UserFromEmailRequest
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index b4d53a92c1a..a6d5cf36358 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -231,3 +231,8 @@ pub enum SignInWithTokenResponse {
Token(TokenResponse),
SignInResponse(SignInResponse),
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct UserFromEmailRequest {
+ pub token: Secret<String>,
+}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 0ae1b162e0e..58a6452c9bb 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -183,21 +183,7 @@ pub async fn signin_token_only_flow(
let next_flow =
domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?;
- let token = match next_flow.get_flow() {
- domain::UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(&state, &next_flow).await,
- domain::UserFlow::JWTFlow(jwt_flow) => {
- #[cfg(feature = "email")]
- {
- user_from_db.get_verification_days_left(&state)?;
- }
-
- let user_role = user_from_db
- .get_preferred_or_active_user_role_from_db(&state)
- .await
- .to_not_found_response(UserErrors::InternalServerError)?;
- jwt_flow.generate_jwt(&state, &next_flow, &user_role).await
- }
- }?;
+ let token = next_flow.get_token(&state).await?;
let response = user_api::SignInWithTokenResponse::Token(user_api::TokenResponse {
token: token.clone(),
@@ -1323,3 +1309,38 @@ pub async fn update_user_details(
Ok(ApplicationResponse::StatusOk)
}
+
+#[cfg(feature = "email")]
+pub async fn user_from_email(
+ state: AppState,
+ req: user_api::UserFromEmailRequest,
+) -> UserResponse<user_api::TokenResponse> {
+ let token = req.token.expose();
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
+ .await
+ .change_context(UserErrors::LinkInvalid)?;
+
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_email(
+ &email_token
+ .get_email()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ let next_flow =
+ domain::NextFlow::from_origin(email_token.get_flow(), user_from_db.clone(), &state).await?;
+
+ let token = next_flow.get_token(&state).await?;
+
+ let response = user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ };
+ auth::cookies::set_cookie_response(response, token)
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 19a632bf895..0f3673ee206 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1201,6 +1201,7 @@ impl User {
#[cfg(feature = "email")]
{
route = route
+ .service(web::resource("/from_email").route(web::post().to(user_from_email)))
.service(
web::resource("/connect_account").route(web::post().to(user_connect_account)),
)
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index faef85f3901..4d1121a8eab 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -219,7 +219,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::DeleteUserRole
| Flow::TransferOrgOwnership
| Flow::CreateRole
- | Flow::UpdateRole => Self::UserRole,
+ | Flow::UpdateRole
+ | Flow::UserFromEmail => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 4d841913bc0..ede6edbceb8 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -512,3 +512,22 @@ pub async fn update_user_account_details(
))
.await
}
+
+#[cfg(feature = "email")]
+pub async fn user_from_email(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_api::UserFromEmailRequest>,
+) -> HttpResponse {
+ let flow = Flow::UserFromEmail;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, _: (), req_body, _| user_core::user_from_email(state, req_body),
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 323f98a56df..ee51d976b40 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -151,6 +151,7 @@ Email : {user_email}
pub struct EmailToken {
email: String,
merchant_id: Option<String>,
+ flow: domain::Origin,
exp: u64,
}
@@ -158,6 +159,7 @@ impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
merchant_id: Option<String>,
+ flow: domain::Origin,
settings: &configs::Settings,
) -> CustomResult<String, UserErrors> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
@@ -165,6 +167,7 @@ impl EmailToken {
let token_payload = Self {
email: email.get_secret().expose(),
merchant_id,
+ flow,
exp,
};
jwt::generate_jwt(&token_payload, settings).await
@@ -177,6 +180,10 @@ impl EmailToken {
pub fn get_merchant_id(&self) -> Option<&str> {
self.merchant_id.as_deref()
}
+
+ pub fn get_flow(&self) -> domain::Origin {
+ self.flow.clone()
+ }
}
pub fn get_link_with_token(
@@ -197,9 +204,14 @@ pub struct VerifyEmail {
#[async_trait::async_trait]
impl EmailData for VerifyEmail {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings)
- .await
- .change_context(EmailError::TokenGenerationFailure)?;
+ let token = EmailToken::new_token(
+ self.recipient_email.clone(),
+ None,
+ domain::Origin::VerifyEmail,
+ &self.settings,
+ )
+ .await
+ .change_context(EmailError::TokenGenerationFailure)?;
let verify_email_link =
get_link_with_token(&self.settings.email.base_url, token, "verify_email");
@@ -226,9 +238,14 @@ pub struct ResetPassword {
#[async_trait::async_trait]
impl EmailData for ResetPassword {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings)
- .await
- .change_context(EmailError::TokenGenerationFailure)?;
+ let token = EmailToken::new_token(
+ self.recipient_email.clone(),
+ None,
+ domain::Origin::ResetPassword,
+ &self.settings,
+ )
+ .await
+ .change_context(EmailError::TokenGenerationFailure)?;
let reset_password_link =
get_link_with_token(&self.settings.email.base_url, token, "set_password");
@@ -256,9 +273,14 @@ pub struct MagicLink {
#[async_trait::async_trait]
impl EmailData for MagicLink {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings)
- .await
- .change_context(EmailError::TokenGenerationFailure)?;
+ let token = EmailToken::new_token(
+ self.recipient_email.clone(),
+ None,
+ domain::Origin::MagicLink,
+ &self.settings,
+ )
+ .await
+ .change_context(EmailError::TokenGenerationFailure)?;
let magic_link_login =
get_link_with_token(&self.settings.email.base_url, token, "verify_email");
@@ -276,6 +298,7 @@ impl EmailData for MagicLink {
}
}
+// TODO: Deprecate this and use InviteRegisteredUser for new invites
pub struct InviteUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
@@ -290,6 +313,7 @@ impl EmailData for InviteUser {
let token = EmailToken::new_token(
self.recipient_email.clone(),
Some(self.merchant_id.clone()),
+ domain::Origin::ResetPassword,
&self.settings,
)
.await
@@ -310,6 +334,7 @@ impl EmailData for InviteUser {
})
}
}
+
pub struct InviteRegisteredUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
@@ -324,6 +349,7 @@ impl EmailData for InviteRegisteredUser {
let token = EmailToken::new_token(
self.recipient_email.clone(),
Some(self.merchant_id.clone()),
+ domain::Origin::AcceptInvitationFromEmail,
&self.settings,
)
.await
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index b5aff779106..e460bc74649 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -4,7 +4,7 @@ use masking::Secret;
use super::UserFromStorage;
use crate::{
- core::errors::{UserErrors, UserResult},
+ core::errors::{StorageErrorExt, UserErrors, UserResult},
routes::AppState,
services::authentication as auth,
};
@@ -225,6 +225,25 @@ impl NextFlow {
pub fn get_flow(&self) -> UserFlow {
self.next_flow
}
+
+ pub async fn get_token(&self, state: &AppState) -> UserResult<Secret<String>> {
+ match self.next_flow {
+ UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
+ UserFlow::JWTFlow(jwt_flow) => {
+ #[cfg(feature = "email")]
+ {
+ self.user.get_verification_days_left(state)?;
+ }
+
+ let user_role = self
+ .user
+ .get_preferred_or_active_user_role_from_db(state)
+ .await
+ .to_not_found_response(UserErrors::InternalServerError)?;
+ jwt_flow.generate_jwt(state, self, &user_role).await
+ }
+ }
+ }
}
impl From<UserFlow> for TokenPurpose {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 26cb619d74c..78f570f647e 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -394,6 +394,8 @@ pub enum Flow {
CreateRole,
/// Update Role
UpdateRole,
+ /// User email flow start
+ UserFromEmail,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-05-03T08:52: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 -->
- Create a new API `from_email` which will take email token and give the token for the next flow.
- Add `flow` field in email token which will help `from_email` API to decide the next flow.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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 #4532
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/from_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
Response should be like this
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDYxNjE1YjAtZjI5Yi00NWIyLWJmNmItODczNTYyYWU1ODhlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJtYWdpY19saW5rIiwiZXhwIjoxNzE0ODExOTAwfQ.CDErXJ89a1o3ROyAKvm6TFW1drHDnlcqg43OoBQjY6A",
"token_type": "totp"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
83a192466849c5fd201296e7554644a025ced888
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4534
|
Bug: [BUG] [BAMBORA] Payments Failing Due to Wrong Card Expiry Year
### Bug Description
Payments are failing for connector Bambora due to wrong format of card expiry year.
### Expected Behavior
Only 2 digit i.e. `25` for `2025` card expiry year should be passed in Bambora Payments Request.
### Actual Behavior
The system is allowing both 2 digit and 4 digit card expiry year in Bambora Payments Request.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index 0717b997bad..7ff352416cd 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -62,6 +62,10 @@ impl ConnectorCommon for Bambora {
"bambora"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -187,7 +191,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
"{}/v1/payments/{}{}",
self.base_url(connectors),
connector_payment_id,
- "/completions"
+ "/void"
))
}
@@ -196,7 +200,22 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraPaymentsRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request
+ .currency
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "Currency",
+ })?,
+ req.request
+ .amount
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "Amount",
+ })?,
+ req,
+ ))?;
+
+ let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -376,7 +395,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraPaymentsCaptureRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+
+ let connector_req =
+ bambora::BamboraPaymentsCaptureRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -470,7 +497,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraPaymentsRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+
+ let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -569,7 +603,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraRefundRequest::try_from(req)?;
+ let connector_router_data = bambora::BamboraRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req = bambora::BamboraRefundRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 3115f04f483..dbb655c6ca0 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -5,13 +5,46 @@ use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
- connector::utils::{BrowserInformationData, PaymentsAuthorizeRequestData, RouterData},
+ connector::utils::{
+ AddressDetailsData, BrowserInformationData, CardData as OtherCardData,
+ PaymentsAuthorizeRequestData, RouterData,
+ },
consts,
core::errors,
services,
types::{self, api, domain, storage::enums},
};
+pub struct BamboraRouterData<T> {
+ pub amount: f64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for BamboraRouterData<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 = crate::connector::utils::get_amount_as_f64(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraCard {
name: Secret<String>,
@@ -46,16 +79,21 @@ pub struct BamboraBrowserInfo {
javascript_enabled: bool,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Default, Debug, Serialize)]
pub struct BamboraPaymentsRequest {
order_number: String,
- amount: i64,
+ amount: f64,
payment_method: PaymentMethod,
customer_ip: Option<Secret<String, IpAddress>>,
term_url: Option<String>,
card: BamboraCard,
}
+#[derive(Default, Debug, Serialize)]
+pub struct BamboraVoidRequest {
+ amount: f64,
+}
+
fn get_browser_info(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<BamboraBrowserInfo>, error_stack::Report<errors::ConnectorError>> {
@@ -102,41 +140,41 @@ impl TryFrom<&types::CompleteAuthorizeData> for BamboraThreedsContinueRequest {
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
+impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for BamboraPaymentsRequest {
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: BamboraRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
domain::PaymentMethodData::Card(req_card) => {
- let three_ds = match item.auth_type {
+ let three_ds = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => Some(ThreeDSecure {
enabled: true,
- browser: get_browser_info(item)?,
+ browser: get_browser_info(item.router_data)?,
version: Some(2),
auth_required: Some(true),
}),
enums::AuthenticationType::NoThreeDs => None,
};
let bambora_card = BamboraCard {
- name: item
- .get_optional_billing_full_name()
- .unwrap_or(Secret::new("".to_string())),
+ name: item.router_data.get_billing_address()?.get_full_name()?,
+ expiry_year: req_card.get_card_expiry_year_2_digit()?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
cvd: req_card.card_cvc,
three_d_secure: three_ds,
- complete: item.request.is_auto_capture()?,
+ complete: item.router_data.request.is_auto_capture()?,
};
- let browser_info = item.request.get_browser_info()?;
+ let browser_info = item.router_data.request.get_browser_info()?;
Ok(Self {
- order_number: item.connector_request_reference_id.clone(),
- amount: item.request.amount,
+ order_number: item.router_data.connector_request_reference_id.clone(),
+ amount: item.amount,
payment_method: PaymentMethod::Card,
card: bambora_card,
customer_ip: browser_info
.ip_address
.map(|ip_address| Secret::new(format!("{ip_address}"))),
- term_url: item.request.complete_authorize_url.clone(),
+ term_url: item.router_data.request.complete_authorize_url.clone(),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
@@ -144,12 +182,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
}
}
-impl TryFrom<&types::PaymentsCancelRouterData> for BamboraPaymentsRequest {
+impl TryFrom<BamboraRouterData<&types::PaymentsCancelRouterData>> for BamboraVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: BamboraRouterData<&types::PaymentsCancelRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: 0,
- ..Default::default()
+ amount: item.amount,
})
}
}
@@ -417,15 +456,19 @@ pub enum PaymentMethod {
// Capture
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
pub struct BamboraPaymentsCaptureRequest {
- amount: Option<i64>,
+ amount: Option<f64>,
payment_method: PaymentMethod,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for BamboraPaymentsCaptureRequest {
+impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
+ for BamboraPaymentsCaptureRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: BamboraRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: Some(item.request.amount_to_capture),
+ amount: Some(item.amount),
payment_method: PaymentMethod::Card,
})
}
@@ -433,16 +476,18 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for BamboraPaymentsCaptureReques
// REFUND :
// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Default, Debug, Serialize)]
pub struct BamboraRefundRequest {
- amount: i64,
+ amount: f64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for BamboraRefundRequest {
+impl<F> TryFrom<BamboraRouterData<&types::RefundsRouterData<F>>> for BamboraRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: BamboraRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.request.refund_amount,
+ amount: item.amount,
})
}
}
|
2024-05-03T10:28:04Z
|
## 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 the following changes for connector Bambora:
- Only 2 digit i.e. `25` for `2025` card expiry year will be allowed be pass in Bambora Payments Request.
- Amount will be passed in decimal format for Authorize, Capture and Refund requests.
- Fix Void Flow.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4534
https://github.com/juspay/hyperswitch/issues/4538
## How did you test 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 (Manual):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"capture_method": "manual",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
```
Response:
```
{
"payment_id": "pay_LKthlJrz33C1pr55C7ib",
"merchant_id": "merchant_1714730521",
"status": "requires_capture",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 2500,
"amount_received": null,
"connector": "bambora",
"client_secret": "pay_LKthlJrz33C1pr55C7ib_secret_BaVLQyDPAxLkJFEXfCXD",
"created": "2024-05-03T11:30:29.586Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": "40300000",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1714735829,
"expires": 1714739429,
"secret": "epk_74a8cad9f3c64a229b4236f6999b8c67"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004723",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_LKthlJrz33C1pr55C7ib_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-03T11:45:29.586Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-03T11:30:31.543Z"
}
```
- Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_Bnr8RRNohtyOwlEvTOjg/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response:
```
{
"payment_id": "pay_Bnr8RRNohtyOwlEvTOjg",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": 2500,
"connector": "bambora",
"client_secret": "pay_Bnr8RRNohtyOwlEvTOjg_secret_F7JoawvBWk3zzTJ9o3a8",
"created": "2024-05-03T11:27:21.382Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": "40300000",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "10004714",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_Bnr8RRNohtyOwlEvTOjg_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-03T11:42:21.382Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-03T11:27:32.674Z"
}
```
- Payments (Automatic Capture):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
```
Response:
```
{
"payment_id": "pay_7KsO7eanoa25U0NUwGMy",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": 2500,
"connector": "bambora",
"client_secret": "pay_7KsO7eanoa25U0NUwGMy_secret_MIVHZVOHOByIuQyxzs8H",
"created": "2024-05-03T11:36:55.259Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": "40300000",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1714736215,
"expires": 1714739815,
"secret": "epk_ec99b66693a14bf180eba0f525c07cd0"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004725",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_7KsO7eanoa25U0NUwGMy_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-03T11:51:55.258Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-03T11:36:57.592Z"
}
```
- Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_id": "pay_Bf0CmzVjSJCBVt5e6n3m",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_ksDchUYhgBlvAYz2maZ2",
"payment_id": "pay_Bf0CmzVjSJCBVt5e6n3m",
"amount": 2500,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-05-03T11:38:14.960Z",
"updated_at": "2024-05-03T11:38:14.960Z",
"connector": "bambora",
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
17b369cfabc42d4d06f65b92e967057dba348731
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4521
|
Bug: [REFACTOR] Update AnalyticsPool to hold variables for tenant ID
Update the [AnalyticsProvider](https://github.com/juspay/hyperswitch/blob/be44447c09ea8814dc8b88aa971e08cc749db5f3/crates/analytics/src/lib.rs#L67-L72) (or [`AnalyticsConfig`](https://github.com/juspay/hyperswitch/blob/be44447c09ea8814dc8b88aa971e08cc749db5f3/crates/analytics/src/lib.rs#L593-L608)) to hold a variable for tenant-ID.
This can be achieved by simply adding a new field in the underlying structs for SqlxClient & ClickhouseClient.
Update the AnalyticsPool constructor method to accept a Tenant-ID.
Tenant-ID can be a new type field backed by a string;
pub struct TenantID(String);
For now the AnalyticsPool can be initialized with a fixed tenantID "default"
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 81516ee8b6b..30f33430378 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -639,6 +639,7 @@ sdk_eligible_payment_methods = "card"
[multitenancy]
enabled = false
+global_tenant = { schema = "public", redis_key_prefix = "" }
[multitenancy.tenants]
-public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant
\ No newline at end of file
+public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant
\ No newline at end of file
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 9ab790b8ee8..162444c9098 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -256,6 +256,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
[multitenancy]
enabled = false
+global_tenant = { schema = "public", redis_key_prefix = "" }
[multitenancy.tenants]
-public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""}
\ No newline at end of file
+public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
\ No newline at end of file
diff --git a/config/development.toml b/config/development.toml
index 9a40a99cfce..b986a66d845 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -648,6 +648,7 @@ sdk_eligible_payment_methods = "card"
[multitenancy]
enabled = false
+global_tenant = { schema = "public", redis_key_prefix = "" }
[multitenancy.tenants]
-public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""}
+public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2cd93eade01..a9d37995728 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -502,6 +502,7 @@ sdk_eligible_payment_methods = "card"
[multitenancy]
enabled = false
+global_tenant = { schema = "public", redis_key_prefix = "" }
[multitenancy.tenants]
-public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""}
\ No newline at end of file
+public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
\ No newline at end of file
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 64064c09c88..fd1746c4b9e 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -35,6 +35,7 @@ pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>;
#[derive(Clone, Debug)]
pub struct ClickhouseClient {
pub config: Arc<ClickhouseConfig>,
+ pub database: String,
}
#[derive(Clone, Debug, serde::Deserialize)]
@@ -42,7 +43,6 @@ pub struct ClickhouseConfig {
username: String,
password: Option<String>,
host: String,
- database_name: String,
}
impl Default for ClickhouseConfig {
@@ -51,7 +51,6 @@ impl Default for ClickhouseConfig {
username: "default".to_string(),
password: None,
host: "http://localhost:8123".to_string(),
- database_name: "default".to_string(),
}
}
}
@@ -63,7 +62,7 @@ impl ClickhouseClient {
let params = CkhQuery {
date_time_output_format: String::from("iso"),
output_format_json_quote_64bit_integers: 0,
- database: self.config.database_name.clone(),
+ database: self.database.clone(),
};
let response = client
.post(&self.config.host)
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index f658f679097..5c269a4bb18 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -601,22 +601,30 @@ impl AnalyticsProvider {
}
}
- pub async fn from_conf(config: &AnalyticsConfig, tenant: &str) -> Self {
+ pub async fn from_conf(
+ config: &AnalyticsConfig,
+ tenant: &dyn storage_impl::config::ClickHouseConfig,
+ ) -> Self {
match config {
- AnalyticsConfig::Sqlx { sqlx } => Self::Sqlx(SqlxClient::from_conf(sqlx, tenant).await),
+ AnalyticsConfig::Sqlx { sqlx } => {
+ Self::Sqlx(SqlxClient::from_conf(sqlx, tenant.get_schema()).await)
+ }
AnalyticsConfig::Clickhouse { clickhouse } => Self::Clickhouse(ClickhouseClient {
config: Arc::new(clickhouse.clone()),
+ database: tenant.get_clickhouse_database().to_string(),
}),
AnalyticsConfig::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh(
- SqlxClient::from_conf(sqlx, tenant).await,
+ SqlxClient::from_conf(sqlx, tenant.get_schema()).await,
ClickhouseClient {
config: Arc::new(clickhouse.clone()),
+ database: tenant.get_clickhouse_database().to_string(),
},
),
AnalyticsConfig::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx(
- SqlxClient::from_conf(sqlx, tenant).await,
+ SqlxClient::from_conf(sqlx, tenant.get_schema()).await,
ClickhouseClient {
config: Arc::new(clickhouse.clone()),
+ database: tenant.get_clickhouse_database().to_string(),
},
),
}
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 968ef22bf97..38c8997358d 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -87,8 +87,8 @@ pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2;
/// Default tenant to be used when multitenancy is disabled
pub const DEFAULT_TENANT: &str = "public";
-/// Global tenant to be used when multitenancy is enabled
-pub const GLOBAL_TENANT: &str = "global";
+/// Default tenant to be used when multitenancy is disabled
+pub const TENANT_HEADER: &str = "x-tenant-id";
/// Max Length for MerchantReferenceId
pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64;
diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs
index dac515cb279..2bd403a847b 100644
--- a/crates/diesel_models/src/query/user.rs
+++ b/crates/diesel_models/src/query/user.rs
@@ -1,23 +1,9 @@
-use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::pii;
-use diesel::{
- associations::HasTable, debug_query, result::Error as DieselError, ExpressionMethods,
- JoinOnDsl, QueryDsl,
-};
-use error_stack::report;
-use router_env::logger;
+use diesel::{associations::HasTable, ExpressionMethods};
pub mod sample_data;
use crate::{
- errors::{self},
- query::generics,
- schema::{
- user_roles::{self, dsl as user_roles_dsl},
- users::dsl as users_dsl,
- },
- user::*,
- user_role::UserRole,
- PgPooledConn, StorageResult,
+ query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult,
};
impl UserNew {
@@ -90,27 +76,6 @@ impl User {
.await
}
- pub async fn find_joined_users_and_roles_by_merchant_id(
- conn: &PgPooledConn,
- mid: &str,
- ) -> StorageResult<Vec<(Self, UserRole)>> {
- let query = Self::table()
- .inner_join(user_roles::table.on(user_roles_dsl::user_id.eq(users_dsl::user_id)))
- .filter(user_roles_dsl::merchant_id.eq(mid.to_owned()));
-
- logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
-
- query
- .get_results_async::<(Self, UserRole)>(conn)
- .await
- .map_err(|err| match err {
- DieselError::NotFound => {
- report!(err).change_context(errors::DatabaseError::NotFound)
- }
- _ => report!(err).change_context(errors::DatabaseError::Others),
- })
- }
-
pub async fn find_users_by_user_ids(
conn: &PgPooledConn,
user_ids: Vec<String>,
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs
index e64b5dbd4ad..57c17f577b1 100644
--- a/crates/drainer/src/settings.rs
+++ b/crates/drainer/src/settings.rs
@@ -143,6 +143,7 @@ pub struct Tenant {
pub base_url: String,
pub schema: String,
pub redis_key_prefix: String,
+ pub clickhouse_database: String,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index e99e216463a..f3f70cf42bd 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -128,6 +128,7 @@ pub struct Settings<S: SecretState> {
pub struct Multitenancy {
pub tenants: TenantConfig,
pub enabled: bool,
+ pub global_tenant: GlobalTenant,
}
impl Multitenancy {
@@ -152,6 +153,7 @@ pub struct Tenant {
pub base_url: String,
pub schema: String,
pub redis_key_prefix: String,
+ pub clickhouse_database: String,
}
impl storage_impl::config::TenantConfig for Tenant {
@@ -163,6 +165,12 @@ impl storage_impl::config::TenantConfig for Tenant {
}
}
+impl storage_impl::config::ClickHouseConfig for Tenant {
+ fn get_clickhouse_database(&self) -> &str {
+ self.clickhouse_database.as_str()
+ }
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct GlobalTenant {
pub schema: String,
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index e1601f8bbbe..7b9919d3afa 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -1,3 +1,4 @@
+use common_utils::consts::TENANT_HEADER;
use futures::StreamExt;
use router_env::{
logger,
@@ -140,10 +141,17 @@ where
// TODO: have a common source of truth for the list of top level fields
// /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS
fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future {
+ let tenant_id = req
+ .headers()
+ .get(TENANT_HEADER)
+ .and_then(|i| i.to_str().ok())
+ .map(|s| s.to_owned());
let response_fut = self.service.call(req);
-
Box::pin(
async move {
+ if let Some(tenant_id) = tenant_id {
+ router_env::tracing::Span::current().record("tenant_id", &tenant_id);
+ }
let response = response_fut.await;
router_env::tracing::Span::current().record("golden_log_line", true);
response
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 92ca3c264fe..2e7a6c4f61e 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -5,7 +5,6 @@ use actix_web::{web, Scope};
use api_models::routing::RoutingRetrieveQuery;
#[cfg(feature = "olap")]
use common_enums::TransactionType;
-use common_utils::consts::{DEFAULT_TENANT, GLOBAL_TENANT};
#[cfg(feature = "email")]
use external_services::email::{ses::AwsSes, EmailService};
use external_services::file_storage::FileStorageInterface;
@@ -257,19 +256,11 @@ impl AppState {
let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
.await
.expect("Failed to create store");
- let global_tenant = if conf.multitenancy.enabled {
- GLOBAL_TENANT
- } else {
- DEFAULT_TENANT
- };
let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface(
&storage_impl,
&event_handler,
&conf,
- &settings::GlobalTenant {
- schema: global_tenant.to_string(),
- redis_key_prefix: String::default(),
- },
+ &conf.multitenancy.global_tenant,
Arc::clone(&cache_store),
testable,
)
@@ -288,9 +279,7 @@ impl AppState {
.get_storage_interface();
stores.insert(tenant_name.clone(), store);
#[cfg(feature = "olap")]
- let pool =
- AnalyticsProvider::from_conf(conf.analytics.get_inner(), tenant_name.as_str())
- .await;
+ let pool = AnalyticsProvider::from_conf(conf.analytics.get_inner(), tenant).await;
#[cfg(feature = "olap")]
pools.insert(tenant_name.clone(), pool);
}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index baa824ced3f..7408f379489 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -19,7 +19,7 @@ use api_models::enums::{CaptureMethod, PaymentMethodType};
pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient};
pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
- consts::X_HS_LATENCY,
+ consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
request::RequestContent,
};
@@ -941,10 +941,10 @@ where
.into_iter()
.collect();
let tenant_id = if !state.conf.multitenancy.enabled {
- common_utils::consts::DEFAULT_TENANT.to_string()
+ DEFAULT_TENANT.to_string()
} else {
incoming_request_header
- .get("x-tenant-id")
+ .get(TENANT_HEADER)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())
.map(|req_tenant_id| {
diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs
index e371936a04d..bb006b6a9e5 100644
--- a/crates/storage_impl/src/config.rs
+++ b/crates/storage_impl/src/config.rs
@@ -38,6 +38,10 @@ pub trait TenantConfig: Send + Sync {
fn get_redis_key_prefix(&self) -> &str;
}
+pub trait ClickHouseConfig: TenantConfig + Send + Sync {
+ fn get_clickhouse_database(&self) -> &str;
+}
+
#[derive(Debug, serde::Deserialize, Clone, Copy, Default)]
#[serde(rename_all = "PascalCase")]
pub enum QueueStrategy {
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index d008ff3231c..ad97ef6d404 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -328,6 +328,7 @@ keys = "user-agent"
[multitenancy]
enabled = false
+global_tenant = { schema = "public", redis_key_prefix = "" }
[multitenancy.tenants]
-public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""}
\ No newline at end of file
+public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
\ No newline at end of file
|
2024-06-04T11:18:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add Tenant_id as a field for all logs
Add Tenant_id action for Kafka messages as well , headers to be a combination of ( tenant_id, merchant_id, payment_id )
Make logical databases and physical tables in clickhouse for different tenants
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
To establish tenancy in our application and start using the default tenant as 'Hyperswitch' and also offer a 'test' tenant in all environments
https://github.com/juspay/hyperswitch-product/issues/50
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Since there is no new changes involved, sanity testing is enough, Check if the payments are going fine and able to see analytics in dashboard
## 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
|
18493bd8f03b933b15bc3c40b3501222587fc59f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4509
|
Bug: feat(user): get user information (home api)
Create new api to get user details.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 9884dbc4f41..8f017ca8c20 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -12,10 +12,11 @@ use crate::user::{
},
AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetUserDetailsRequest, GetUserDetailsResponse, InviteUserRequest, ListUsersResponse,
- ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest, SignInResponse,
- SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
- UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest,
+ GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
+ InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
+ SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
+ SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate,
+ VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -60,8 +61,9 @@ common_utils::impl_misc_api_event_type!(
AcceptInviteFromEmailRequest,
SignInResponse,
UpdateUserAccountDetailsRequest,
- GetUserDetailsRequest,
- GetUserDetailsResponse
+ GetUserDetailsResponse,
+ GetUserRoleDetailsRequest,
+ GetUserRoleDetailsResponse
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 9b3d7a2e654..700c27461cd 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -149,13 +149,25 @@ pub struct UserDetails {
pub last_modified_at: time::PrimitiveDateTime,
}
+#[derive(serde::Serialize, Debug, Clone)]
+pub struct GetUserDetailsResponse {
+ pub merchant_id: String,
+ pub name: Secret<String>,
+ pub email: pii::Email,
+ pub verification_days_left: Option<i64>,
+ pub role_id: String,
+ // This field is added for audit/debug reasons
+ #[serde(skip_serializing)]
+ pub user_id: String,
+ pub org_id: String,
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct GetUserDetailsRequest {
+pub struct GetUserRoleDetailsRequest {
pub email: pii::Email,
}
#[derive(Debug, serde::Serialize)]
-pub struct GetUserDetailsResponse {
+pub struct GetUserRoleDetailsResponse {
pub email: pii::Email,
pub name: Secret<String>,
pub role_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 71d18774cb8..2e439a6eb52 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -71,6 +71,26 @@ pub async fn signup_with_merchant_id(
}))
}
+pub async fn get_user_details(
+ state: AppState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_api::GetUserDetailsResponse> {
+ let user = user_from_token.get_user_from_db(&state).await?;
+ let verification_days_left = utils::user::get_verification_days_left(&state, &user)?;
+
+ Ok(ApplicationResponse::Json(
+ user_api::GetUserDetailsResponse {
+ merchant_id: user_from_token.merchant_id,
+ name: user.get_name(),
+ email: user.get_email(),
+ user_id: user.get_user_id().to_string(),
+ verification_days_left,
+ role_id: user_from_token.role_id,
+ org_id: user_from_token.org_id,
+ },
+ ))
+}
+
pub async fn signup(
state: AppState,
request: user_api::SignUpRequest,
@@ -1001,9 +1021,9 @@ pub async fn list_merchants_for_user(
pub async fn get_user_details_in_merchant_account(
state: AppState,
user_from_token: auth::UserFromToken,
- request: user_api::GetUserDetailsRequest,
+ request: user_api::GetUserRoleDetailsRequest,
_req_state: ReqState,
-) -> UserResponse<user_api::GetUserDetailsResponse> {
+) -> UserResponse<user_api::GetUserRoleDetailsResponse> {
let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?)
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
@@ -1029,7 +1049,7 @@ pub async fn get_user_details_in_merchant_account(
.attach_printable("User role exists but the corresponding role doesn't")?;
Ok(ApplicationResponse::Json(
- user_api::GetUserDetailsResponse {
+ user_api::GetUserRoleDetailsResponse {
email: required_user.get_email(),
name: required_user.get_name(),
role_id: role_info.get_role_id().to_string(),
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 595fd26f92c..4311b9b96e2 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1160,6 +1160,7 @@ impl User {
let mut route = web::scope("/user").app_data(web::Data::new(state));
route = route
+ .service(web::resource("").route(web::get().to(get_user_details)))
.service(web::resource("/v2/signin").route(web::post().to(user_signin)))
.service(web::resource("/signout").route(web::post().to(signout)))
.service(web::resource("/change_password").route(web::post().to(change_password)))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index de87f7fce53..c5a3157d817 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -197,6 +197,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::DeleteSampleData
| Flow::UserMerchantAccountList
| Flow::GetUserDetails
+ | Flow::GetUserRoleDetails
| Flow::ListUsersForMerchantAccount
| Flow::ForgotPassword
| Flow::ResetPassword
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index bf3ddbc4491..0657d781b08 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -19,6 +19,20 @@ use crate::{
utils::user::dashboard_metadata::{parse_string_to_enums, set_ip_address_if_required},
};
+pub async fn get_user_details(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::GetUserDetails;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, user, _, _| user_core::get_user_details(state, user),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "email")]
pub async fn user_signup_with_merchant_id(
state: web::Data<AppState>,
@@ -295,7 +309,7 @@ pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpReques
pub async fn get_user_role_details(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Query<user_api::GetUserDetailsRequest>,
+ payload: web::Query<user_api::GetUserRoleDetailsRequest>,
) -> HttpResponse {
let flow = Flow::GetUserDetails;
Box::pin(api::server_wrap(
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 9dfdb6a57a8..da5afbdc75c 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -348,8 +348,10 @@ pub enum Flow {
DeleteSampleData,
/// List merchant accounts for user
UserMerchantAccountList,
- /// Get details of a user in a merchant account
+ /// Get details of a user
GetUserDetails,
+ /// Get details of a user role in a merchant account
+ GetUserRoleDetails,
/// List users for merchant account
ListUsersForMerchantAccount,
/// PaymentMethodAuth Link token create
|
2024-04-30T14:02:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add support to get user details!
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
closes #4509
## How did you test it?
Use the curl to get user info:
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response will be, something like:
```
{
"merchant_id": "merchant_1714396883",
"name": "test1",
"email": "apoorvdixit88+555@gmail.com",
"verification_days_left": null,
"role_id": "merchant_view_only",
"org_id": "org_HomVKdwu2HGTi6jUvvnz"
}
```
## Checklist
<!-- Put an `x` in 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
|
b0133f33693575f2145d295eff78dd07b61efcda
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4502
|
Bug: [BUG] Fix failing postman tests for Paypal
### Bug Description
Postman tests for Paypal fail in the access token flow.
### Expected Behavior
All postman tests should pass
### Actual Behavior
The tests fail
### Steps To Reproduce
Run the paypal postman tests
### Context For The Bug
_No response_
### Environment
Local
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/postman/collection-dir/paypal/event.prerequest.js b/postman/collection-dir/paypal/event.prerequest.js
index f4c9a764864..944aebeb6ee 100644
--- a/postman/collection-dir/paypal/event.prerequest.js
+++ b/postman/collection-dir/paypal/event.prerequest.js
@@ -3,25 +3,28 @@ const isPostRequest = pm.request.method.toString() === "POST";
const isPaymentCreation = path.match(/\/payments$/) && isPostRequest;
if (isPaymentCreation) {
- try {
- const request = JSON.parse(pm.request.body.toJSON().raw);
+ try {
+ const request = JSON.parse(pm.request.body.toJSON().raw);
+ const merchantConnectorId = pm.collectionVariables.get("merchant_connector_id");
- // Attach routing
- const routing = { type: "single", data: "paypal" };
- request["routing"] = routing;
+ // Attach routing
+ const routing = {
+ type: "single", data: { connector: "paypal", merchant_connector_id: merchantConnectorId }
+ };
+ request["routing"] = routing;
- let updatedRequest = {
- mode: "raw",
- raw: JSON.stringify(request),
- options: {
- raw: {
- language: "json",
- },
- },
- };
- pm.request.body.update(updatedRequest);
- } catch (error) {
- console.error("Failed to inject routing in the request");
- console.error(error);
- }
-}
\ No newline at end of file
+ let updatedRequest = {
+ mode: "raw",
+ raw: JSON.stringify(request),
+ options: {
+ raw: {
+ language: "json",
+ },
+ },
+ };
+ pm.request.body.update(updatedRequest);
+ } catch (error) {
+ console.error("Failed to inject routing in the request");
+ console.error(error);
+ }
+}
diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json
index dfb52bb4ffc..58368b3b856 100644
--- a/postman/collection-json/paypal.postman_collection.json
+++ b/postman/collection-json/paypal.postman_collection.json
@@ -9,28 +9,32 @@
"const isPaymentCreation = path.match(/\\/payments$/) && isPostRequest;",
"",
"if (isPaymentCreation) {",
- " try {",
- " const request = JSON.parse(pm.request.body.toJSON().raw);",
+ " try {",
+ " const request = JSON.parse(pm.request.body.toJSON().raw);",
+ " const merchantConnectorId = pm.collectionVariables.get(\"merchant_connector_id\");",
"",
- " // Attach routing",
- " const routing = { type: \"single\", data: \"paypal\" };",
- " request[\"routing\"] = routing;",
+ " // Attach routing",
+ " const routing = {",
+ " type: \"single\", data: { connector: \"paypal\", merchant_connector_id: merchantConnectorId }",
+ " };",
+ " request[\"routing\"] = routing;",
"",
- " let updatedRequest = {",
- " mode: \"raw\",",
- " raw: JSON.stringify(request),",
- " options: {",
- " raw: {",
- " language: \"json\",",
- " },",
- " },",
- " };",
- " pm.request.body.update(updatedRequest);",
- " } catch (error) {",
- " console.error(\"Failed to inject routing in the request\");",
- " console.error(error);",
- " }",
- "}"
+ " let updatedRequest = {",
+ " mode: \"raw\",",
+ " raw: JSON.stringify(request),",
+ " options: {",
+ " raw: {",
+ " language: \"json\",",
+ " },",
+ " },",
+ " };",
+ " pm.request.body.update(updatedRequest);",
+ " } catch (error) {",
+ " console.error(\"Failed to inject routing in the request\");",
+ " console.error(error);",
+ " }",
+ "}",
+ ""
],
"type": "text/javascript"
}
|
2024-04-30T07:39:01Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR fixes a failing Paypal Postman test. The issue occurred because the `merchant_connector_id` was not being passed in the `routing` parameter in the request, which is not compatible with the access token flow currently. This PR adds the `merchant_connector_id` parameter to the request.
Additionally, @Narayanbhat166 will add compatibility support to the access token flow for cases where the `merchant_connector_id` is missing
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Running all Paypal postman tests locally.
<img width="518" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/48a79b42-2776-4021-86bb-c9137088ddc0">
## Checklist
<!-- Put an `x` in 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
|
28df646830f544179b7cf00eb8f51de2a606bdbc
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4517
|
Bug: feat: decision manger for user flows
As we are going to split all the APIs, we need a way to get the next API that dashboard should go to using the current flow/origin.
We need a decision manager that can take the current flow and origin and give the next flow.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 8f017ca8c20..594b60b5816 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -14,9 +14,9 @@ use crate::user::{
CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
- SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
- SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate,
- VerifyEmailRequest,
+ SendVerifyEmailRequest, SignInResponse, SignInWithTokenResponse, SignUpRequest,
+ SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest,
+ UserMerchantCreate, VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -62,6 +62,7 @@ common_utils::impl_misc_api_event_type!(
SignInResponse,
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
+ SignInWithTokenResponse,
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 700c27461cd..b4d53a92c1a 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -1,4 +1,4 @@
-use common_enums::{PermissionGroup, RoleScope};
+use common_enums::{PermissionGroup, RoleScope, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, pii};
use masking::Secret;
@@ -213,3 +213,21 @@ pub struct UpdateUserAccountDetailsRequest {
pub name: Option<Secret<String>>,
pub preferred_merchant_id: Option<String>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TokenOnlyQueryParam {
+ pub token_only: Option<bool>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TokenResponse {
+ pub token: Secret<String>,
+ pub token_type: TokenPurpose,
+}
+
+#[derive(Debug, serde::Serialize)]
+#[serde(untagged)]
+pub enum SignInWithTokenResponse {
+ Token(TokenResponse),
+ SignInResponse(SignInResponse),
+}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 18545eb4a4d..3c86064731b 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2706,3 +2706,17 @@ pub enum BankHolderType {
Personal,
Business,
}
+
+#[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum TokenPurpose {
+ #[serde(rename = "totp")]
+ #[strum(serialize = "totp")]
+ TOTP,
+ VerifyEmail,
+ AcceptInvitationFromEmail,
+ ResetPassword,
+ AcceptInvite,
+ UserInfo,
+}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 2e439a6eb52..0ae1b162e0e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -123,7 +123,7 @@ pub async fn signup(
pub async fn signin(
state: AppState,
request: user_api::SignInRequest,
-) -> UserResponse<user_api::SignInResponse> {
+) -> UserResponse<user_api::SignInWithTokenResponse> {
let user_from_db: domain::UserFromStorage = state
.store
.find_user_by_email(&request.email)
@@ -161,6 +161,48 @@ pub async fn signin(
let response = signin_strategy.get_signin_response(&state).await?;
let token = utils::user::get_token_from_signin_response(&response);
+ auth::cookies::set_cookie_response(
+ user_api::SignInWithTokenResponse::SignInResponse(response),
+ token,
+ )
+}
+
+pub async fn signin_token_only_flow(
+ state: AppState,
+ request: user_api::SignInRequest,
+) -> UserResponse<user_api::SignInWithTokenResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_email(&request.email)
+ .await
+ .to_not_found_response(UserErrors::InvalidCredentials)?
+ .into();
+
+ user_from_db.compare_password(request.password)?;
+
+ let next_flow =
+ domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?;
+
+ let token = match next_flow.get_flow() {
+ domain::UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(&state, &next_flow).await,
+ domain::UserFlow::JWTFlow(jwt_flow) => {
+ #[cfg(feature = "email")]
+ {
+ user_from_db.get_verification_days_left(&state)?;
+ }
+
+ let user_role = user_from_db
+ .get_preferred_or_active_user_role_from_db(&state)
+ .await
+ .to_not_found_response(UserErrors::InternalServerError)?;
+ jwt_flow.generate_jwt(&state, &next_flow, &user_role).await
+ }
+ }?;
+
+ let response = user_api::SignInWithTokenResponse::Token(user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ });
auth::cookies::set_cookie_response(response, token)
}
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 0657d781b08..4d841913bc0 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -76,15 +76,23 @@ pub async fn user_signin(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignInRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignIn;
let req_payload = json_payload.into_inner();
+ let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
- |state, _, req_body, _| user_core::signin(state, req_body),
+ |state, _, req_body, _| async move {
+ if let Some(true) = is_token_only {
+ user_core::signin_token_only_flow(state, req_body).await
+ } else {
+ user_core::signin(state, req_body).await
+ }
+ },
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 7247c858f4d..59c07b79855 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,5 +1,6 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::user_role::{self as user_role_api, role as role_api};
+use common_enums::TokenPurpose;
use router_env::Flow;
use super::AppState;
@@ -214,7 +215,7 @@ pub async fn accept_invitation(
&req,
payload,
user_role_core::accept_invitation,
- &auth::SinglePurposeJWTAuth(auth::Purpose::AcceptInvite),
+ &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index c49ad81d919..5f15474115d 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -4,6 +4,7 @@ use api_models::{
payments,
};
use async_trait::async_trait;
+use common_enums::TokenPurpose;
use common_utils::date_time;
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
@@ -66,7 +67,7 @@ pub enum AuthenticationType {
},
SinglePurposeJWT {
user_id: String,
- purpose: Purpose,
+ purpose: TokenPurpose,
},
MerchantId {
merchant_id: String,
@@ -113,28 +114,28 @@ impl AuthenticationType {
}
}
+#[cfg(feature = "olap")]
#[derive(Clone, Debug)]
pub struct UserFromSinglePurposeToken {
pub user_id: String,
+ pub origin: domain::Origin,
}
+#[cfg(feature = "olap")]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct SinglePurposeToken {
pub user_id: String,
- pub purpose: Purpose,
+ pub purpose: TokenPurpose,
+ pub origin: domain::Origin,
pub exp: u64,
}
-#[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)]
-pub enum Purpose {
- AcceptInvite,
-}
-
#[cfg(feature = "olap")]
impl SinglePurposeToken {
pub async fn new_token(
user_id: String,
- purpose: Purpose,
+ purpose: TokenPurpose,
+ origin: domain::Origin,
settings: &Settings,
) -> UserResult<String> {
let exp_duration =
@@ -143,6 +144,7 @@ impl SinglePurposeToken {
let token_payload = Self {
user_id,
purpose,
+ origin,
exp,
};
jwt::generate_jwt(&token_payload, settings).await
@@ -308,8 +310,9 @@ where
}
}
+#[cfg(feature = "olap")]
#[derive(Debug)]
-pub(crate) struct SinglePurposeJWTAuth(pub Purpose);
+pub(crate) struct SinglePurposeJWTAuth(pub TokenPurpose);
#[cfg(feature = "olap")]
#[async_trait]
@@ -334,6 +337,7 @@ where
Ok((
UserFromSinglePurposeToken {
user_id: payload.user_id.clone(),
+ origin: payload.origin.clone(),
},
AuthenticationType::SinglePurposeJWT {
user_id: payload.user_id,
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index bc11ee19089..c1abb064752 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -5,7 +5,9 @@ use common_utils::date_time;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
-use super::{AuthToken, SinglePurposeToken};
+use super::AuthToken;
+#[cfg(feature = "olap")]
+use super::SinglePurposeToken;
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
@@ -154,6 +156,7 @@ impl BlackList for AuthToken {
}
}
+#[cfg(feature = "olap")]
#[async_trait::async_trait]
impl BlackList for SinglePurposeToken {
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index fab02df88ba..b4b5df2f46c 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -3,6 +3,7 @@ use std::{collections::HashSet, ops, str::FromStr};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
+use common_enums::TokenPurpose;
use common_utils::{errors::CustomResult, pii};
use diesel_models::{
enums::UserStatus,
@@ -31,6 +32,8 @@ use crate::{
};
pub mod dashboard_metadata;
+pub mod decision_manager;
+pub use decision_manager::*;
#[derive(Clone)]
pub struct UserName(Secret<String>);
@@ -785,6 +788,29 @@ impl UserFromStorage {
.find_user_role_by_user_id_merchant_id(self.get_user_id(), merchant_id)
.await
}
+
+ pub async fn get_preferred_or_active_user_role_from_db(
+ &self,
+ state: &AppState,
+ ) -> CustomResult<UserRole, errors::StorageError> {
+ if let Some(preferred_merchant_id) = self.get_preferred_merchant_id() {
+ self.get_role_from_db_by_merchant_id(state, &preferred_merchant_id)
+ .await
+ } else {
+ state
+ .store
+ .list_user_roles_by_user_id(&self.0.user_id)
+ .await?
+ .into_iter()
+ .find(|role| role.status == UserStatus::Active)
+ .ok_or(
+ errors::StorageError::ValueNotFound(
+ "No active role found for user".to_string(),
+ )
+ .into(),
+ )
+ }
+ }
}
impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
@@ -912,7 +938,8 @@ impl SignInWithMultipleRolesStrategy {
email: self.user.get_email(),
token: auth::SinglePurposeToken::new_token(
self.user.get_user_id().to_string(),
- auth::Purpose::AcceptInvite,
+ TokenPurpose::AcceptInvite,
+ Origin::SignIn,
&state.conf,
)
.await?
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
new file mode 100644
index 00000000000..b5aff779106
--- /dev/null
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -0,0 +1,257 @@
+use common_enums::TokenPurpose;
+use diesel_models::{enums::UserStatus, user_role::UserRole};
+use masking::Secret;
+
+use super::UserFromStorage;
+use crate::{
+ core::errors::{UserErrors, UserResult},
+ routes::AppState,
+ services::authentication as auth,
+};
+
+#[derive(Eq, PartialEq, Clone, Copy)]
+pub enum UserFlow {
+ SPTFlow(SPTFlow),
+ JWTFlow(JWTFlow),
+}
+
+impl UserFlow {
+ async fn is_required(&self, user: &UserFromStorage, state: &AppState) -> UserResult<bool> {
+ match self {
+ Self::SPTFlow(flow) => flow.is_required(user, state).await,
+ Self::JWTFlow(flow) => flow.is_required(user, state).await,
+ }
+ }
+}
+
+#[derive(Eq, PartialEq, Clone, Copy)]
+pub enum SPTFlow {
+ TOTP,
+ VerifyEmail,
+ AcceptInvitationFromEmail,
+ ForceSetPassword,
+ MerchantSelect,
+ ResetPassword,
+}
+
+impl SPTFlow {
+ async fn is_required(&self, user: &UserFromStorage, state: &AppState) -> UserResult<bool> {
+ match self {
+ // TOTP
+ Self::TOTP => Ok(true),
+ // Main email APIs
+ Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
+ Self::VerifyEmail => Ok(user.0.is_verified),
+ // Final Checks
+ // TODO: this should be based on last_password_modified_at as a placeholder using false
+ Self::ForceSetPassword => Ok(false),
+ Self::MerchantSelect => user
+ .get_roles_from_db(state)
+ .await
+ .map(|roles| !roles.iter().any(|role| role.status == UserStatus::Active)),
+ }
+ }
+
+ pub async fn generate_spt(
+ self,
+ state: &AppState,
+ next_flow: &NextFlow,
+ ) -> UserResult<Secret<String>> {
+ auth::SinglePurposeToken::new_token(
+ next_flow.user.get_user_id().to_string(),
+ self.into(),
+ next_flow.origin.clone(),
+ &state.conf,
+ )
+ .await
+ .map(|token| token.into())
+ }
+}
+
+#[derive(Eq, PartialEq, Clone, Copy)]
+pub enum JWTFlow {
+ UserInfo,
+}
+
+impl JWTFlow {
+ async fn is_required(&self, _user: &UserFromStorage, _state: &AppState) -> UserResult<bool> {
+ Ok(true)
+ }
+
+ pub async fn generate_jwt(
+ self,
+ state: &AppState,
+ next_flow: &NextFlow,
+ user_role: &UserRole,
+ ) -> UserResult<Secret<String>> {
+ auth::AuthToken::new_token(
+ next_flow.user.get_user_id().to_string(),
+ user_role.merchant_id.clone(),
+ user_role.role_id.clone(),
+ &state.conf,
+ user_role.org_id.clone(),
+ )
+ .await
+ .map(|token| token.into())
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
+#[serde(rename_all = "snake_case")]
+pub enum Origin {
+ SignIn,
+ SignUp,
+ MagicLink,
+ VerifyEmail,
+ AcceptInvitationFromEmail,
+ ResetPassword,
+}
+
+impl Origin {
+ fn get_flows(&self) -> &'static [UserFlow] {
+ match self {
+ Self::SignIn => &SIGNIN_FLOW,
+ Self::SignUp => &SIGNUP_FLOW,
+ Self::VerifyEmail => &VERIFY_EMAIL_FLOW,
+ Self::MagicLink => &MAGIC_LINK_FLOW,
+ Self::AcceptInvitationFromEmail => &ACCEPT_INVITATION_FROM_EMAIL_FLOW,
+ Self::ResetPassword => &RESET_PASSWORD_FLOW,
+ }
+ }
+}
+
+const SIGNIN_FLOW: [UserFlow; 4] = [
+ UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
+ UserFlow::SPTFlow(SPTFlow::MerchantSelect),
+ UserFlow::JWTFlow(JWTFlow::UserInfo),
+];
+
+const SIGNUP_FLOW: [UserFlow; 4] = [
+ UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
+ UserFlow::SPTFlow(SPTFlow::MerchantSelect),
+ UserFlow::JWTFlow(JWTFlow::UserInfo),
+];
+
+const MAGIC_LINK_FLOW: [UserFlow; 5] = [
+ UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::VerifyEmail),
+ UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
+ UserFlow::SPTFlow(SPTFlow::MerchantSelect),
+ UserFlow::JWTFlow(JWTFlow::UserInfo),
+];
+
+const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [
+ UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::VerifyEmail),
+ UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
+ UserFlow::SPTFlow(SPTFlow::MerchantSelect),
+ UserFlow::JWTFlow(JWTFlow::UserInfo),
+];
+
+const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 4] = [
+ UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail),
+ UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
+ UserFlow::JWTFlow(JWTFlow::UserInfo),
+];
+
+const RESET_PASSWORD_FLOW: [UserFlow; 2] = [
+ UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::ResetPassword),
+];
+
+pub struct CurrentFlow {
+ origin: Origin,
+ current_flow_index: usize,
+}
+
+impl CurrentFlow {
+ pub fn new(origin: Origin, current_flow: UserFlow) -> UserResult<Self> {
+ let flows = origin.get_flows();
+ let index = flows
+ .iter()
+ .position(|flow| flow == ¤t_flow)
+ .ok_or(UserErrors::InternalServerError)?;
+
+ Ok(Self {
+ origin,
+ current_flow_index: index,
+ })
+ }
+
+ pub async fn next(&self, user: UserFromStorage, state: &AppState) -> UserResult<NextFlow> {
+ let flows = self.origin.get_flows();
+ let remaining_flows = flows.iter().skip(self.current_flow_index + 1);
+ for flow in remaining_flows {
+ if flow.is_required(&user, state).await? {
+ return Ok(NextFlow {
+ origin: self.origin.clone(),
+ next_flow: *flow,
+ user,
+ });
+ }
+ }
+ Err(UserErrors::InternalServerError.into())
+ }
+}
+
+pub struct NextFlow {
+ origin: Origin,
+ next_flow: UserFlow,
+ user: UserFromStorage,
+}
+
+impl NextFlow {
+ pub async fn from_origin(
+ origin: Origin,
+ user: UserFromStorage,
+ state: &AppState,
+ ) -> UserResult<Self> {
+ let flows = origin.get_flows();
+ for flow in flows {
+ if flow.is_required(&user, state).await? {
+ return Ok(Self {
+ origin,
+ next_flow: *flow,
+ user,
+ });
+ }
+ }
+ Err(UserErrors::InternalServerError.into())
+ }
+
+ pub fn get_flow(&self) -> UserFlow {
+ self.next_flow
+ }
+}
+
+impl From<UserFlow> for TokenPurpose {
+ fn from(value: UserFlow) -> Self {
+ match value {
+ UserFlow::SPTFlow(flow) => flow.into(),
+ UserFlow::JWTFlow(flow) => flow.into(),
+ }
+ }
+}
+
+impl From<SPTFlow> for TokenPurpose {
+ fn from(value: SPTFlow) -> Self {
+ match value {
+ SPTFlow::TOTP => Self::TOTP,
+ SPTFlow::VerifyEmail => Self::VerifyEmail,
+ SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
+ SPTFlow::MerchantSelect => Self::AcceptInvite,
+ SPTFlow::ResetPassword | SPTFlow::ForceSetPassword => Self::ResetPassword,
+ }
+ }
+}
+
+impl From<JWTFlow> for TokenPurpose {
+ fn from(value: JWTFlow) -> Self {
+ match value {
+ JWTFlow::UserInfo => Self::UserInfo,
+ }
+ }
+}
|
2024-05-02T07:47:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- This PR will enable APIs to get the next flow from the current flow.
- This PR will also add a query param which will enable to access the new flows.
### 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 #4517.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}'
```
Should return with the following response
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDYxNjE1YjAtZjI5Yi00NWIyLWJmNmItODczNTYyYWU1ODhlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJTaWduSW4iLCJleHAiOjE3MTQ3MTk2NDh9.GOO-ZM3KDk0yjmNo3y8SgjqCcIYCV96Lj-lhmNl2oOc",
"token_type": "totp"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
6c59d2434ce5067611d85d37b7ec6f551b7ad81a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4523
|
Bug: [FEATURE] Move struct RouterData to crate hyperswitch_domain_models
### Feature Description
RouterData will move to crate `hyperswitch_domain_models`.
### Possible Implementation
RouterData will be moved to crate `hyperswitch_domain_models`.
### 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 b823f9e5c96..5ba2d0dae6d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3647,6 +3647,7 @@ dependencies = [
"common_utils",
"diesel_models",
"error-stack",
+ "http 0.2.12",
"masking",
"serde",
"serde_json",
diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index 760e1528cfa..cecf5ef1c60 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -7,7 +7,7 @@ use masking::ExposeInterface;
use crate::{
events::connector_api_logs::ConnectorEvent,
configs::settings,
- utils::{self, BytesExt},
+ utils::BytesExt,
core::{
errors::{self, CustomResult},
},
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs
index 60b13693054..0d9e99c86a4 100644
--- a/connector-template/transformers.rs
+++ b/connector-template/transformers.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use masking::Secret;
-use crate::{connector::utils::{PaymentsAuthorizeRequestData},core::errors,types::{self,api, storage::enums}};
+use crate::{connector::utils::{PaymentsAuthorizeRequestData},core::errors,types::{self, domain, api, storage::enums}};
//TODO: Fill the struct with respective fields
pub struct {{project-name | downcase | pascal_case}}RouterData<T> {
@@ -53,7 +53,7 @@ impl TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&types::Paymen
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&types::PaymentsAuthorizeRouterData>) -> Result<Self,Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- api::PaymentMethodData::Card(req_card) => {
+ domain::PaymentMethodData::Card(req_card) => {
let card = {{project-name | downcase | pascal_case}}Card {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index 58eff10a363..dd3335cb2c0 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -23,6 +23,7 @@ diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_
# Third party deps
async-trait = "0.1.79"
error-stack = "0.4.1"
+http = "0.2.12"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
thiserror = "1.0.58"
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 30279fae549..b470b538d78 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -1,8 +1,10 @@
pub mod errors;
pub mod mandates;
+pub mod payment_address;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
+pub mod router_data;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
diff --git a/crates/hyperswitch_domain_models/src/payment_address.rs b/crates/hyperswitch_domain_models/src/payment_address.rs
new file mode 100644
index 00000000000..d4f2cf9f350
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/payment_address.rs
@@ -0,0 +1,82 @@
+use api_models::payments::Address;
+
+#[derive(Clone, Default, Debug)]
+pub struct PaymentAddress {
+ shipping: Option<Address>,
+ billing: Option<Address>,
+ unified_payment_method_billing: Option<Address>,
+ payment_method_billing: Option<Address>,
+}
+
+impl PaymentAddress {
+ pub fn new(
+ shipping: Option<Address>,
+ billing: Option<Address>,
+ payment_method_billing: Option<Address>,
+ should_unify_address: Option<bool>,
+ ) -> Self {
+ // billing -> .billing, this is the billing details passed in the root of payments request
+ // payment_method_billing -> .payment_method_data.billing
+
+ let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
+ // Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
+ // The unified payment_method_billing will be used as billing address and passed to the connector module
+ // This unification is required in order to provide backwards compatibility
+ // so that if `payment.billing` is passed it should be sent to the connector module
+ // Unify the billing details with `payment_method_data.billing`
+ payment_method_billing
+ .as_ref()
+ .map(|payment_method_billing| {
+ payment_method_billing
+ .clone()
+ .unify_address(billing.as_ref())
+ })
+ .or(billing.clone())
+ } else {
+ payment_method_billing.clone()
+ };
+
+ Self {
+ shipping,
+ billing,
+ unified_payment_method_billing,
+ payment_method_billing,
+ }
+ }
+
+ pub fn get_shipping(&self) -> Option<&Address> {
+ self.shipping.as_ref()
+ }
+
+ pub fn get_payment_method_billing(&self) -> Option<&Address> {
+ self.unified_payment_method_billing.as_ref()
+ }
+
+ /// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
+ pub fn unify_with_payment_method_data_billing(
+ self,
+ payment_method_data_billing: Option<Address>,
+ ) -> Self {
+ // Unify the billing details with `payment_method_data.billing_details`
+ let unified_payment_method_billing = payment_method_data_billing
+ .map(|payment_method_data_billing| {
+ payment_method_data_billing.unify_address(self.get_payment_method_billing())
+ })
+ .or(self.get_payment_method_billing().cloned());
+
+ Self {
+ shipping: self.shipping,
+ billing: self.billing,
+ unified_payment_method_billing,
+ payment_method_billing: self.payment_method_billing,
+ }
+ }
+
+ pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
+ self.payment_method_billing.as_ref()
+ }
+
+ pub fn get_payment_billing(&self) -> Option<&Address> {
+ self.billing.as_ref()
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
new file mode 100644
index 00000000000..cbaaeeda42b
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -0,0 +1,207 @@
+use std::{collections::HashMap, marker::PhantomData};
+
+use masking::Secret;
+
+use crate::payment_address::PaymentAddress;
+
+#[derive(Debug, Clone)]
+pub struct RouterData<Flow, Request, Response> {
+ pub flow: PhantomData<Flow>,
+ pub merchant_id: String,
+ pub customer_id: Option<String>,
+ pub connector_customer: Option<String>,
+ pub connector: String,
+ pub payment_id: String,
+ pub attempt_id: String,
+ pub status: common_enums::enums::AttemptStatus,
+ pub payment_method: common_enums::enums::PaymentMethod,
+ pub connector_auth_type: ConnectorAuthType,
+ pub description: Option<String>,
+ pub return_url: Option<String>,
+ pub address: PaymentAddress,
+ pub auth_type: common_enums::enums::AuthenticationType,
+ pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
+ pub amount_captured: Option<i64>,
+ pub access_token: Option<AccessToken>,
+ pub session_token: Option<String>,
+ pub reference_id: Option<String>,
+ pub payment_method_token: Option<PaymentMethodToken>,
+ pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
+ pub preprocessing_id: Option<String>,
+ /// This is the balance amount for gift cards or voucher
+ pub payment_method_balance: Option<PaymentMethodBalance>,
+
+ ///for switching between two different versions of the same connector
+ pub connector_api_version: Option<String>,
+
+ /// Contains flow-specific data required to construct a request and send it to the connector.
+ pub request: Request,
+
+ /// Contains flow-specific data that the connector responds with.
+ pub response: Result<Response, ErrorResponse>,
+
+ /// Contains a reference ID that should be sent in the connector request
+ pub connector_request_reference_id: String,
+
+ #[cfg(feature = "payouts")]
+ /// Contains payout method data
+ pub payout_method_data: Option<api_models::payouts::PayoutMethodData>,
+
+ #[cfg(feature = "payouts")]
+ /// Contains payout's quote ID
+ pub quote_id: Option<String>,
+
+ pub test_mode: Option<bool>,
+ pub connector_http_status_code: Option<u16>,
+ pub external_latency: Option<u128>,
+ /// Contains apple pay flow type simplified or manual
+ pub apple_pay_flow: Option<common_enums::enums::ApplePayFlow>,
+
+ pub frm_metadata: Option<serde_json::Value>,
+
+ pub dispute_id: Option<String>,
+ pub refund_id: Option<String>,
+
+ /// This field is used to store various data regarding the response from connector
+ pub connector_response: Option<ConnectorResponseData>,
+ pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
+}
+
+// Different patterns of authentication.
+#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(tag = "auth_type")]
+pub enum ConnectorAuthType {
+ TemporaryAuth,
+ HeaderKey {
+ api_key: Secret<String>,
+ },
+ BodyKey {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ },
+ SignatureKey {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ api_secret: Secret<String>,
+ },
+ MultiAuthKey {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ api_secret: Secret<String>,
+ key2: Secret<String>,
+ },
+ CurrencyAuthKey {
+ auth_key_map: HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>,
+ },
+ CertificateAuth {
+ certificate: Secret<String>,
+ private_key: Secret<String>,
+ },
+ #[default]
+ NoKey,
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
+pub struct AccessToken {
+ pub token: Secret<String>,
+ pub expires: i64,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub enum PaymentMethodToken {
+ Token(Secret<String>),
+ ApplePayDecrypt(Box<ApplePayPredecryptData>),
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ApplePayPredecryptData {
+ pub application_primary_account_number: Secret<String>,
+ pub application_expiration_date: String,
+ pub currency_code: String,
+ pub transaction_amount: i64,
+ pub device_manufacturer_identifier: Secret<String>,
+ pub payment_data_type: Secret<String>,
+ pub payment_data: ApplePayCryptogramData,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ApplePayCryptogramData {
+ pub online_payment_cryptogram: Secret<String>,
+ pub eci_indicator: Option<String>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct RecurringMandatePaymentData {
+ pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
+ pub original_payment_authorized_amount: Option<i64>,
+ pub original_payment_authorized_currency: Option<common_enums::enums::Currency>,
+}
+
+#[derive(Debug, Clone)]
+pub struct PaymentMethodBalance {
+ pub amount: i64,
+ pub currency: common_enums::enums::Currency,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ConnectorResponseData {
+ pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
+}
+
+impl ConnectorResponseData {
+ pub fn with_additional_payment_method_data(
+ additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
+ ) -> Self {
+ Self {
+ additional_payment_method_data: Some(additional_payment_method_data),
+ }
+ }
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub enum AdditionalPaymentMethodConnectorResponse {
+ Card {
+ /// Details regarding the authentication details of the connector, if this is a 3ds payment.
+ authentication_data: Option<serde_json::Value>,
+ /// Various payment checks that are done for a payment
+ payment_checks: Option<serde_json::Value>,
+ },
+}
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct ErrorResponse {
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+ pub status_code: u16,
+ pub attempt_status: Option<common_enums::enums::AttemptStatus>,
+ pub connector_transaction_id: Option<String>,
+}
+
+impl Default for ErrorResponse {
+ fn default() -> Self {
+ Self {
+ code: "HE_00".to_string(),
+ message: "Something went wrong".to_string(),
+ reason: None,
+ status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
+ attempt_status: None,
+ connector_transaction_id: None,
+ }
+ }
+}
+
+impl ErrorResponse {
+ pub fn get_not_implemented() -> Self {
+ Self {
+ code: "IR_00".to_string(),
+ message: "This API is under development and will be made available soon.".to_string(),
+ reason: None,
+ status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
+ attempt_status: None,
+ connector_transaction_id: None,
+ }
+ }
+}
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 943eedf87dd..f80b8725f2a 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -30,7 +30,7 @@ use crate::{
self,
api::{self, ConnectorCommon},
domain,
- transformers::ForeignFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
@@ -364,7 +364,7 @@ impl
req: &types::SetupMandateRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let authorize_req = types::PaymentsAuthorizeRouterData::from((
+ let authorize_req = types::PaymentsAuthorizeRouterData::foreign_from((
req,
types::PaymentsAuthorizeData::from(req),
));
@@ -419,7 +419,7 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
@@ -703,7 +703,7 @@ impl
types::SyncRequestType::MultipleCaptureSync(_) => true,
types::SyncRequestType::SinglePaymentSync => false,
};
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
@@ -830,7 +830,7 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 9dd523b73c7..ab01f9e70ce 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -3808,7 +3808,7 @@ pub fn get_present_to_shopper_metadata(
}
impl<F, Req>
- TryFrom<(
+ ForeignTryFrom<(
types::ResponseRouterData<F, AdyenPaymentResponse, Req, types::PaymentsResponseData>,
Option<storage_enums::CaptureMethod>,
bool,
@@ -3816,7 +3816,7 @@ impl<F, Req>
)> for types::RouterData<F, Req, types::PaymentsResponseData>
{
type Error = Error;
- fn try_from(
+ fn foreign_try_from(
(item, capture_method, is_multiple_capture_psync_flow, pmt): (
types::ResponseRouterData<F, AdyenPaymentResponse, Req, types::PaymentsResponseData>,
Option<storage_enums::CaptureMethod>,
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index bdd842bf958..ca511534b97 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -1,5 +1,4 @@
pub mod transformers;
-
use std::fmt::Debug;
use common_utils::{
@@ -28,6 +27,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignFrom,
ErrorResponse, Response, RouterData,
},
utils::{crypto, BytesExt},
@@ -349,7 +349,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
+ Sync
+ 'static),
> = Box::new(&Self);
- let authorize_data = &types::PaymentsInitRouterData::from((
+ let authorize_data = &types::PaymentsInitRouterData::foreign_from((
&router_data.to_owned(),
router_data.request.clone(),
));
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 2ca78e630fa..0eb4297a414 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -1,5 +1,4 @@
pub mod transformers;
-
use std::fmt::Debug;
use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
@@ -24,6 +23,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt, PaymentsCompleteAuthorize},
+ transformers::ForeignTryFrom,
},
utils::BytesExt,
};
@@ -218,7 +218,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
@@ -410,7 +410,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
@@ -791,7 +791,7 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index ca8b13298b0..ddcfdfacad2 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -17,7 +17,7 @@ use crate::{
api::{self, enums as api_enums},
domain,
storage::enums,
- transformers::ForeignFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
@@ -620,7 +620,7 @@ impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
}
impl<F, T>
- TryFrom<(
+ ForeignTryFrom<(
types::ResponseRouterData<
F,
AuthorizedotnetPaymentsResponse,
@@ -631,7 +631,7 @@ impl<F, T>
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
+ fn foreign_try_from(
(item, is_auto_capture): (
types::ResponseRouterData<
F,
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 1e8a167a179..4a5d99023cf 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -375,7 +375,7 @@ impl<F, T>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::from((
+ types::AdditionalPaymentMethodConnectorResponse::foreign_from((
processor_information,
consumer_auth_information,
))
@@ -422,7 +422,10 @@ impl<F, T>
})
}
BankOfAmericaSetupMandatesResponse::ErrorInformation(ref error_response) => {
- let response = Err(types::ErrorResponse::from((error_response, item.http_code)));
+ let response = Err(types::ErrorResponse::foreign_from((
+ error_response,
+ item.http_code,
+ )));
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
@@ -1538,13 +1541,13 @@ pub struct BankOfAmericaErrorInformation {
}
impl<F, T>
- From<(
+ ForeignFrom<(
&BankOfAmericaErrorInformationResponse,
types::ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, types::PaymentsResponseData>,
Option<enums::AttemptStatus>,
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
- fn from(
+ fn foreign_from(
(error_response, item, transaction_status): (
&BankOfAmericaErrorInformationResponse,
types::ResponseRouterData<
@@ -1594,7 +1597,7 @@ fn get_error_response_if_failure(
),
) -> Option<types::ErrorResponse> {
if utils::is_payment_failure(status) {
- Some(types::ErrorResponse::from((
+ Some(types::ErrorResponse::foreign_from((
&info_response.error_information,
&info_response.risk_information,
Some(status),
@@ -1993,7 +1996,7 @@ impl<F>
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
- let response = Err(types::ErrorResponse::from((
+ let response = Err(types::ErrorResponse::foreign_from((
&info_response.error_information,
&risk_info,
Some(status),
@@ -2055,7 +2058,10 @@ impl<F>
}
}
BankOfAmericaPreProcessingResponse::ErrorInformation(ref error_response) => {
- let response = Err(types::ErrorResponse::from((error_response, item.http_code)));
+ let response = Err(types::ErrorResponse::foreign_from((
+ error_response,
+ item.http_code,
+ )));
Ok(Self {
response,
status: enums::AttemptStatus::AuthenticationFailed,
@@ -2102,7 +2108,7 @@ impl<F>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::from((
+ types::AdditionalPaymentMethodConnectorResponse::foreign_from((
processor_information,
consumer_auth_information,
))
@@ -2130,7 +2136,7 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::from((
+ Ok(Self::foreign_from((
&error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
@@ -2175,7 +2181,7 @@ impl<F>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::from((
+ types::AdditionalPaymentMethodConnectorResponse::foreign_from((
processor_information,
consumer_auth_information,
))
@@ -2203,7 +2209,7 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::from((
+ Ok(Self::foreign_from((
&error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
@@ -2214,12 +2220,12 @@ impl<F>
}
impl
- From<(
+ ForeignFrom<(
&ClientProcessorInformation,
&ConsumerAuthenticationInformation,
)> for types::AdditionalPaymentMethodConnectorResponse
{
- fn from(
+ fn foreign_from(
item: (
&ClientProcessorInformation,
&ConsumerAuthenticationInformation,
@@ -2281,7 +2287,7 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::from((&error_response.clone(), item, None)))
+ Ok(Self::foreign_from((&error_response.clone(), item, None)))
}
}
}
@@ -2318,7 +2324,7 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::from((&error_response.clone(), item, None)))
+ Ok(Self::foreign_from((&error_response.clone(), item, None)))
}
}
}
@@ -2396,7 +2402,7 @@ impl<F>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::from((
+ types::AdditionalPaymentMethodConnectorResponse::foreign_from((
processor_information,
consumer_auth_information,
))
@@ -2419,7 +2425,7 @@ impl<F>
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
- response: Err(types::ErrorResponse::from((
+ response: Err(types::ErrorResponse::foreign_from((
&app_response.error_information,
&risk_info,
Some(status),
@@ -2626,7 +2632,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundR
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status.clone());
let response = if utils::is_refund_failure(refund_status) {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&item.response.error_information,
&None,
None,
@@ -2689,7 +2695,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResp
enums::RefundStatus::from(status.clone());
if utils::is_refund_failure(refund_status) {
if status == BankofamericaRefundStatus::Voided {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&Some(BankOfAmericaErrorInformation {
message: Some(consts::REFUND_VOIDED.to_string()),
reason: None,
@@ -2700,7 +2706,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResp
item.response.id.clone(),
)))
} else {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&item.response.error_information,
&None,
None,
@@ -2789,7 +2795,7 @@ pub struct AuthenticationErrorInformation {
}
impl
- From<(
+ ForeignFrom<(
&Option<BankOfAmericaErrorInformation>,
&Option<ClientRiskInformation>,
Option<enums::AttemptStatus>,
@@ -2797,7 +2803,7 @@ impl
String,
)> for types::ErrorResponse
{
- fn from(
+ fn foreign_from(
(error_data, risk_information, attempt_status, status_code, transaction_id): (
&Option<BankOfAmericaErrorInformation>,
&Option<ClientRiskInformation>,
@@ -3059,8 +3065,10 @@ impl From<&domain::GooglePayWalletData> for PaymentInformation {
}
}
-impl From<(&BankOfAmericaErrorInformationResponse, u16)> for types::ErrorResponse {
- fn from((error_response, status_code): (&BankOfAmericaErrorInformationResponse, u16)) -> Self {
+impl ForeignFrom<(&BankOfAmericaErrorInformationResponse, u16)> for types::ErrorResponse {
+ fn foreign_from(
+ (error_response, status_code): (&BankOfAmericaErrorInformationResponse, u16),
+ ) -> Self {
let error_reason = error_response
.error_information
.message
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs
index 3e5e53286e3..372a65af9f3 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/router/src/connector/billwerk/transformers.rs
@@ -178,7 +178,7 @@ impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for Billw
.into());
};
let source = match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(pm_token) => Ok(Secret::new(pm_token)),
+ types::PaymentMethodToken::Token(pm_token) => Ok(pm_token),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_token",
}),
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index bd860e72900..a607d8fc605 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -1324,7 +1324,7 @@ impl
variables: VariablePaymentInput {
input: PaymentInput {
payment_method_id: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token.into(),
+ types::PaymentMethodToken::Token(token) => token,
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
)?,
@@ -1405,7 +1405,7 @@ fn get_braintree_redirect_form(
.client_token
.expose(),
card_token: match payment_method_token {
- types::PaymentMethodToken::Token(token) => token,
+ types::PaymentMethodToken::Token(token) => token.expose(),
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Simplified",
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index cc937c0ef60..ddf65d23aa4 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -294,7 +294,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
domain::WalletData::GooglePay(_) => Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token.into(),
+ types::PaymentMethodToken::Token(token) => token,
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
@@ -306,7 +306,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
types::PaymentMethodToken::Token(apple_pay_payment_token) => {
Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
- token: apple_pay_payment_token.into(),
+ token: apple_pay_payment_token,
}))
}
types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index 7245694bd44..f7d137eff20 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -30,6 +30,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignTryFrom,
ErrorResponse, Response,
},
utils::BytesExt,
@@ -287,7 +288,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
@@ -374,7 +375,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index baea07faa60..d9d164ac201 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -10,7 +10,7 @@ use crate::{
consts,
core::errors,
services,
- types::{self, domain, storage::enums},
+ types::{self, domain, storage::enums, transformers::ForeignTryFrom},
};
#[derive(Debug, Serialize)]
@@ -141,13 +141,13 @@ pub struct CryptopayPaymentsResponse {
}
impl<F, T>
- TryFrom<(
+ ForeignTryFrom<(
types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
diesel_models::enums::Currency,
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
+ fn foreign_try_from(
(item, currency): (
types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
diesel_models::enums::Currency,
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index 763680d7540..43e5660d2b9 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -31,6 +31,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignTryFrom,
},
utils::BytesExt,
};
@@ -1600,7 +1601,7 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 517d406a9d5..a9b1c37ae9c 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -26,7 +26,7 @@ use crate::{
api::{self, enums as api_enums},
domain,
storage::enums,
- transformers::ForeignFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
ApplePayPredecryptData,
},
unimplemented_payment_method,
@@ -1670,13 +1670,13 @@ pub struct CybersourceErrorInformation {
}
impl<F, T>
- From<(
+ ForeignFrom<(
&CybersourceErrorInformationResponse,
types::ResponseRouterData<F, CybersourcePaymentsResponse, T, types::PaymentsResponseData>,
Option<enums::AttemptStatus>,
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
- fn from(
+ fn foreign_from(
(error_response, item, transaction_status): (
&CybersourceErrorInformationResponse,
types::ResponseRouterData<
@@ -1726,7 +1726,7 @@ fn get_error_response_if_failure(
),
) -> Option<types::ErrorResponse> {
if utils::is_payment_failure(status) {
- Some(types::ErrorResponse::from((
+ Some(types::ErrorResponse::foreign_from((
&info_response.error_information,
&info_response.risk_information,
Some(status),
@@ -1822,11 +1822,13 @@ impl<F>
..item.data
})
}
- CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from((
- &error_response.clone(),
- item,
- Some(enums::AttemptStatus::Failure),
- ))),
+ CybersourcePaymentsResponse::ErrorInformation(ref error_response) => {
+ Ok(Self::foreign_from((
+ &error_response.clone(),
+ item,
+ Some(enums::AttemptStatus::Failure),
+ )))
+ }
}
}
}
@@ -2189,7 +2191,7 @@ impl<F>
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
- let response = Err(types::ErrorResponse::from((
+ let response = Err(types::ErrorResponse::foreign_from((
&info_response.error_information,
&risk_info,
Some(status),
@@ -2315,11 +2317,13 @@ impl<F>
..item.data
})
}
- CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from((
- &error_response.clone(),
- item,
- Some(enums::AttemptStatus::Failure),
- ))),
+ CybersourcePaymentsResponse::ErrorInformation(ref error_response) => {
+ Ok(Self::foreign_from((
+ &error_response.clone(),
+ item,
+ Some(enums::AttemptStatus::Failure),
+ )))
+ }
}
}
}
@@ -2368,7 +2372,7 @@ impl<F>
})
}
CybersourcePaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::from((&error_response.clone(), item, None)))
+ Ok(Self::foreign_from((&error_response.clone(), item, None)))
}
}
}
@@ -2405,7 +2409,7 @@ impl<F>
})
}
CybersourcePaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::from((&error_response.clone(), item, None)))
+ Ok(Self::foreign_from((&error_response.clone(), item, None)))
}
}
}
@@ -2516,7 +2520,7 @@ impl<F, T>
}
impl<F, T>
- TryFrom<(
+ ForeignTryFrom<(
types::ResponseRouterData<
F,
CybersourcePaymentsIncrementalAuthorizationResponse,
@@ -2527,7 +2531,7 @@ impl<F, T>
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
+ fn foreign_try_from(
data: (
types::ResponseRouterData<
F,
@@ -2615,7 +2619,7 @@ impl<F>
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
- response: Err(types::ErrorResponse::from((
+ response: Err(types::ErrorResponse::foreign_from((
&app_response.error_information,
&risk_info,
Some(status),
@@ -2733,7 +2737,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, CybersourceRefundRes
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status.clone());
let response = if utils::is_refund_failure(refund_status) {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&item.response.error_information,
&None,
None,
@@ -2784,7 +2788,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncRespon
let refund_status = enums::RefundStatus::from(status.clone());
if utils::is_refund_failure(refund_status) {
if status == CybersourceRefundStatus::Voided {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&Some(CybersourceErrorInformation {
message: Some(consts::REFUND_VOIDED.to_string()),
reason: None,
@@ -2795,7 +2799,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncRespon
item.response.id.clone(),
)))
} else {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&item.response.error_information,
&None,
None,
@@ -3117,7 +3121,7 @@ pub struct AuthenticationErrorInformation {
}
impl
- From<(
+ ForeignFrom<(
&Option<CybersourceErrorInformation>,
&Option<ClientRiskInformation>,
Option<enums::AttemptStatus>,
@@ -3125,7 +3129,7 @@ impl
String,
)> for types::ErrorResponse
{
- fn from(
+ fn foreign_from(
(error_data, risk_information, attempt_status, status_code, transaction_id): (
&Option<CybersourceErrorInformation>,
&Option<ClientRiskInformation>,
diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs
index d98281cb848..d00b0e545a9 100644
--- a/crates/router/src/connector/globalpay.rs
+++ b/crates/router/src/connector/globalpay.rs
@@ -2,7 +2,6 @@ mod requests;
use super::utils as connector_utils;
mod response;
pub mod transformers;
-
use std::fmt::Debug;
use ::common_utils::{errors::ReportSwitchExt, ext_traits::ByteSliceExt, request::RequestContent};
@@ -35,6 +34,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt, PaymentsCompleteAuthorize},
+ transformers::ForeignTryFrom,
ErrorResponse,
},
utils::{crypto, BytesExt},
@@ -547,7 +547,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
types::SyncRequestType::MultipleCaptureSync(_) => true,
types::SyncRequestType::SinglePaymentSync => false,
};
- types::RouterData::try_from((
+ types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index 478da2cf902..6653205c06a 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -17,7 +17,7 @@ use crate::{
consts,
core::errors,
services::{self, RedirectForm},
- types::{self, api, domain, storage::enums, ErrorResponse},
+ types::{self, api, domain, storage::enums, transformers::ForeignTryFrom, ErrorResponse},
};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -279,14 +279,14 @@ impl<F, T>
}
impl
- TryFrom<(
+ ForeignTryFrom<(
types::PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>,
bool,
)> for types::PaymentsSyncRouterData
{
type Error = Error;
- fn try_from(
+ fn foreign_try_from(
(value, is_multiple_capture_sync): (
types::PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>,
bool,
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index 97f1146b506..b94dd73dd27 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -433,7 +433,7 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
},
payer_ip_address,
links: MandateLink {
- customer_bank_account: Secret::new(customer_bank_account),
+ customer_bank_account,
},
},
})
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index e2c3fc66992..4a6c5b314e0 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -175,7 +175,7 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP
CreditCardMethodData {
billing_address: get_billing_details(item.router_data)?,
shipping_address: get_shipping_details(item.router_data)?,
- card_token: Some(Secret::new(match pm_token {
+ card_token: Some(match pm_token {
types::PaymentMethodToken::Token(token) => token,
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(unimplemented_payment_method!(
@@ -184,7 +184,7 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP
"Mollie"
))?
}
- })),
+ }),
},
)))
}
@@ -497,7 +497,7 @@ impl<F, T>
Ok(Self {
status: storage_enums::AttemptStatus::Pending,
payment_method_token: Some(types::PaymentMethodToken::Token(
- item.response.card_token.clone().expose(),
+ item.response.card_token.clone(),
)),
response: Ok(types::PaymentsResponseData::TokenizationResponse {
token: item.response.card_token.expose(),
diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs
index a8a79095d36..117d8f764ff 100644
--- a/crates/router/src/connector/multisafepay.rs
+++ b/crates/router/src/connector/multisafepay.rs
@@ -23,6 +23,7 @@ use crate::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
storage::enums,
+ transformers::ForeignFrom,
ErrorResponse, Response,
},
utils::BytesExt,
@@ -88,7 +89,7 @@ impl ConnectorCommon for Multisafepay {
let attempt_status = Option::<AttemptStatus>::from(response.clone());
- Ok(ErrorResponse::from((
+ Ok(ErrorResponse::foreign_from((
Some(response.error_code.to_string()),
Some(response.error_info.clone()),
Some(response.error_info),
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index f993928d94f..400e5ecd111 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -11,7 +11,7 @@ use crate::{
core::errors,
pii::Secret,
services,
- types::{self, api, domain, storage::enums},
+ types::{self, api, domain, storage::enums, transformers::ForeignFrom},
};
#[derive(Debug, Serialize)]
@@ -671,7 +671,7 @@ impl<F, T>
Ok(Self {
status,
response: if utils::is_payment_failure(status) {
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
payment_response.data.reason_code,
payment_response.data.reason.clone(),
payment_response.data.reason,
@@ -707,7 +707,7 @@ impl<F, T>
MultisafepayAuthResponse::ErrorResponse(error_response) => {
let attempt_status = Option::<AttemptStatus>::from(error_response.clone());
Ok(Self {
- response: Err(types::ErrorResponse::from((
+ response: Err(types::ErrorResponse::foreign_from((
Some(error_response.error_code.to_string()),
Some(error_response.error_info.clone()),
Some(error_response.error_info),
@@ -857,7 +857,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, MultisafepayRefundResp
})
}
MultisafepayRefundResponse::ErrorResponse(error_response) => Ok(Self {
- response: Err(types::ErrorResponse::from((
+ response: Err(types::ErrorResponse::foreign_from((
Some(error_response.error_code.to_string()),
Some(error_response.error_info.clone()),
Some(error_response.error_info),
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs
index 1f9fd861c03..4b8793a8e82 100644
--- a/crates/router/src/connector/nuvei.rs
+++ b/crates/router/src/connector/nuvei.rs
@@ -26,6 +26,7 @@ use crate::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt, InitPayment},
storage::enums,
+ transformers::ForeignFrom,
ErrorResponse, Response,
},
utils::ByteSliceExt,
@@ -536,7 +537,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
+ Sync
+ 'static),
> = Box::new(&Self);
- let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::from((
+ let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&router_data.to_owned(),
types::AuthorizeSessionTokenData::from(&router_data),
));
@@ -564,7 +565,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
+ Sync
+ 'static),
> = Box::new(&Self);
- let init_data = &types::PaymentsInitRouterData::from((
+ let init_data = &types::PaymentsInitRouterData::foreign_from((
&router_data.to_owned(),
router_data.request.clone(),
));
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index b04b8cb4745..bf20eb1a0b5 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -17,7 +17,10 @@ use crate::{
consts,
core::errors,
services,
- types::{self, api, domain, domain::PaymentMethodData, storage::enums, MandateReference},
+ types::{
+ self, api, domain, domain::PaymentMethodData, storage::enums, transformers::ForeignFrom,
+ MandateReference,
+ },
unimplemented_payment_method,
};
@@ -68,7 +71,7 @@ pub struct MandateRequest {
pub struct Pay3dsRequest {
buyer_name: Secret<String>,
buyer_email: pii::Email,
- buyer_key: String,
+ buyer_key: Secret<String>,
payme_sale_id: String,
meta_data_jwt: Secret<String>,
}
@@ -188,7 +191,10 @@ impl<F, T>
let status = enums::AttemptStatus::from(item.response.sale_status.clone());
let response = if is_payment_failure(status) {
// To populate error message in case of failure
- Err(types::ErrorResponse::from((&item.response, item.http_code)))
+ Err(types::ErrorResponse::foreign_from((
+ &item.response,
+ item.http_code,
+ )))
} else {
Ok(types::PaymentsResponseData::try_from(&item.response)?)
};
@@ -200,8 +206,8 @@ impl<F, T>
}
}
-impl From<(&PaymePaySaleResponse, u16)> for types::ErrorResponse {
- fn from((pay_sale_response, http_code): (&PaymePaySaleResponse, u16)) -> Self {
+impl ForeignFrom<(&PaymePaySaleResponse, u16)> for types::ErrorResponse {
+ fn foreign_from((pay_sale_response, http_code): (&PaymePaySaleResponse, u16)) -> Self {
let code = pay_sale_response
.status_error_code
.map(|error_code| error_code.to_string())
@@ -266,7 +272,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay
let status = enums::AttemptStatus::from(transaction_response.sale_status.clone());
let response = if is_payment_failure(status) {
// To populate error message in case of failure
- Err(types::ErrorResponse::from((
+ Err(types::ErrorResponse::foreign_from((
&transaction_response,
item.http_code,
)))
@@ -281,8 +287,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay
}
}
-impl From<(&SaleQuery, u16)> for types::ErrorResponse {
- fn from((sale_query_response, http_code): (&SaleQuery, u16)) -> Self {
+impl ForeignFrom<(&SaleQuery, u16)> for types::ErrorResponse {
+ fn foreign_from((sale_query_response, http_code): (&SaleQuery, u16)) -> Self {
Self {
code: sale_query_response
.sale_error_code
@@ -880,7 +886,7 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_token: Some(types::PaymentMethodToken::Token(
- item.response.buyer_key.clone().expose(),
+ item.response.buyer_key.clone(),
)),
response: Ok(types::PaymentsResponseData::TokenizationResponse {
token: item.response.buyer_key.expose(),
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs
index e7487e795b6..6c54c7019c8 100644
--- a/crates/router/src/connector/shift4.rs
+++ b/crates/router/src/connector/shift4.rs
@@ -25,6 +25,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignFrom,
ErrorResponse,
},
utils::BytesExt,
@@ -229,7 +230,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
+ Sync
+ 'static),
> = Box::new(&Self);
- let init_data = &types::PaymentsInitRouterData::from((
+ let init_data = &types::PaymentsInitRouterData::foreign_from((
&router_data.to_owned(),
router_data.request.clone(),
));
diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs
index 915a9a9ca11..f9a81031b07 100644
--- a/crates/router/src/connector/square.rs
+++ b/crates/router/src/connector/square.rs
@@ -27,6 +27,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignFrom,
ErrorResponse, Response,
},
utils::BytesExt,
@@ -214,7 +215,7 @@ impl
amount: router_data.request.amount,
};
- let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::from((
+ let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&router_data.to_owned(),
authorize_session_token_data,
));
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index c980a4e7494..0de122d5da2 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -258,12 +258,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
let pm_token = item.get_payment_method_token()?;
Ok(Self {
idempotency_key: Secret::new(item.attempt_id.clone()),
- source_id: Secret::new(match pm_token {
+ source_id: match pm_token {
types::PaymentMethodToken::Token(token) => token,
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Square"),
)?,
- }),
+ },
amount_money: SquarePaymentsAmountData {
amount: item.request.amount,
currency: item.request.currency,
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 95e5dbe4f4f..6477b2325e4 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -67,12 +67,12 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
total,
is_refundable: true,
pre_auth,
- payment_method_id: Secret::new(match pm_token {
+ payment_method_id: match pm_token {
types::PaymentMethodToken::Token(token) => token,
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
- }),
+ },
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
@@ -86,12 +86,12 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
total,
is_refundable: true,
pre_auth,
- payment_method_id: Secret::new(match pm_token {
+ payment_method_id: match pm_token {
types::PaymentMethodToken::Token(token) => token,
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
- }),
+ },
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 1e58a144b9d..20c1b4e70f9 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1828,7 +1828,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
};
Some(StripePaymentMethodData::Wallet(
StripeWallet::ApplepayPayment(ApplepayPayment {
- token: Secret::new(payment_method_token),
+ token: payment_method_token,
payment_method_types: StripePaymentMethodType::Card,
}),
))
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 14d856bb09f..6a569e76a62 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -27,11 +27,13 @@ use crate::{
consts,
core::{
errors::{self, ApiErrorResponse, CustomResult},
- payments::{types::AuthenticationData, PaymentData, RecurringMandatePaymentData},
+ payments::{types::AuthenticationData, PaymentData},
},
pii::PeekInterface,
types::{
- self, api, domain, storage::enums as storage_enums, transformers::ForeignTryFrom,
+ self, api, domain,
+ storage::enums as storage_enums,
+ transformers::{ForeignFrom, ForeignTryFrom},
ApplePayPredecryptData, BrowserInformation, PaymentsCancelData, ResponseId,
},
utils::{OptionExt, ValueExt},
@@ -86,7 +88,9 @@ pub trait RouterData {
fn get_customer_id(&self) -> Result<String, Error>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
- fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>;
+ fn get_recurring_mandate_payment_data(
+ &self,
+ ) -> Result<types::RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
@@ -411,7 +415,9 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
.to_owned()
.ok_or_else(missing_field_err("preprocessing_id"))
}
- fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error> {
+ fn get_recurring_mandate_payment_data(
+ &self,
+ ) -> Result<types::RecurringMandatePaymentData, Error> {
self.recurring_mandate_payment_data
.to_owned()
.ok_or_else(missing_field_err("recurring_mandate_payment_data"))
@@ -1545,7 +1551,7 @@ pub trait RecurringMandateData {
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
}
-impl RecurringMandateData for RecurringMandatePaymentData {
+impl RecurringMandateData for types::RecurringMandatePaymentData {
fn get_original_payment_amount(&self) -> Result<i64, Error> {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
@@ -2181,7 +2187,7 @@ pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
}
impl
- From<(
+ ForeignFrom<(
Option<String>,
Option<String>,
Option<String>,
@@ -2190,7 +2196,7 @@ impl
Option<String>,
)> for types::ErrorResponse
{
- fn from(
+ fn foreign_from(
(code, message, reason, http_code, attempt_status, connector_transaction_id): (
Option<String>,
Option<String>,
diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs
index 3a241fe4ed6..667e182b674 100644
--- a/crates/router/src/connector/wise.rs
+++ b/crates/router/src/connector/wise.rs
@@ -27,7 +27,7 @@ use crate::{
utils::BytesExt,
};
#[cfg(feature = "payouts")]
-use crate::{core::payments, routes};
+use crate::{core::payments, routes, types::transformers::ForeignFrom};
#[derive(Debug, Clone)]
pub struct Wise;
@@ -510,7 +510,7 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
) -> CustomResult<(), errors::ConnectorError> {
// Create a quote
let quote_router_data =
- &types::PayoutsRouterData::from((&router_data, router_data.request.clone()));
+ &types::PayoutsRouterData::foreign_from((&router_data, router_data.request.clone()));
let quote_connector_integration: Box<
&(dyn services::ConnectorIntegration<
api::PoQuote,
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index 50ebea24878..144c7d09b13 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -4,16 +4,14 @@ use router_env::tracing::{self, instrument};
use crate::{
core::{
- errors::RouterResult,
- fraud_check::frm_core_types::FrmFulfillmentRequest,
- payments::{helpers, PaymentAddress},
- utils as core_utils,
+ errors::RouterResult, fraud_check::frm_core_types::FrmFulfillmentRequest,
+ payments::helpers, utils as core_utils,
},
errors,
types::{
domain,
fraud_check::{FraudCheckFulfillmentData, FrmFulfillmentRouterData},
- storage, ConnectorAuthType, ErrorResponse, RouterData,
+ storage, ConnectorAuthType, ErrorResponse, PaymentAddress, RouterData,
},
utils, AppState,
};
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index f3b7b384e2d..4e9d07b7f82 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -81,7 +81,8 @@ pub struct MandateGenericData {
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_type: Option<enums::PaymentMethodType>,
pub mandate_data: Option<MandateData>,
- pub recurring_mandate_payment_data: Option<payments::RecurringMandatePaymentData>,
+ pub recurring_mandate_payment_data:
+ Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>,
pub mandate_connector: Option<payments::MandateConnectorDetails>,
pub payment_method_info: Option<diesel_models::PaymentMethod>,
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 1d25db6a0ba..668a4242b06 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -34,9 +34,12 @@ use error_stack::{report, ResultExt};
use events::EventInfo;
use futures::future::join_all;
use helpers::ApplePayData;
-use hyperswitch_domain_models::mandates::{CustomerAcceptance, MandateData};
+use hyperswitch_domain_models::{
+ mandates::{CustomerAcceptance, MandateData},
+ payment_address::PaymentAddress,
+ router_data::RouterData,
+};
use masking::{ExposeInterface, Secret};
-pub use payment_address::PaymentAddress;
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
@@ -117,7 +120,7 @@ where
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
- router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
@@ -756,7 +759,7 @@ where
Res: transformers::ToResponse<PaymentData<F>, Op>,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
- router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
@@ -1386,15 +1389,14 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest>(
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &storage::business_profile::BusinessProfile,
-) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
+) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
- router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>:
- Feature<F, RouterDReq> + Send,
+ RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
@@ -1495,23 +1497,29 @@ where
};
let apple_pay_predecrypt = apple_pay_data
- .parse_value::<router_types::ApplePayPredecryptData>("ApplePayPredecryptData")
+ .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
+ "ApplePayPredecryptData",
+ )
.change_context(errors::ApiErrorResponse::InternalServerError)?;
logger::debug!(?apple_pay_predecrypt);
- router_data.payment_method_token = Some(router_types::PaymentMethodToken::ApplePayDecrypt(
- Box::new(apple_pay_predecrypt),
- ));
+ router_data.payment_method_token = Some(
+ hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(Box::new(
+ apple_pay_predecrypt,
+ )),
+ );
}
let pm_token = router_data
.add_payment_method_token(state, &connector, &tokenization_action)
.await?;
if let Some(payment_method_token) = pm_token.clone() {
- router_data.payment_method_token = Some(router_types::PaymentMethodToken::Token(
- payment_method_token,
- ));
+ router_data.payment_method_token = Some(
+ hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new(
+ payment_method_token,
+ )),
+ );
};
(router_data, should_continue_further) = complete_preprocessing_steps_if_required(
@@ -1657,7 +1665,7 @@ where
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
- router_types::RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>,
+ RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>,
// To construct connector flow specific api
dyn api::Connector:
@@ -1771,7 +1779,7 @@ where
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
- router_types::RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
+ RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
// To construct connector flow specific api
dyn api::Connector:
@@ -1863,17 +1871,14 @@ async fn complete_preprocessing_steps_if_required<F, Req, Q>(
state: &AppState,
connector: &api::ConnectorData,
payment_data: &PaymentData<F>,
- mut router_data: router_types::RouterData<F, Req, router_types::PaymentsResponseData>,
+ mut router_data: RouterData<F, Req, router_types::PaymentsResponseData>,
operation: &BoxedOperation<'_, F, Q>,
should_continue_payment: bool,
-) -> RouterResult<(
- router_types::RouterData<F, Req, router_types::PaymentsResponseData>,
- bool,
-)>
+) -> RouterResult<(RouterData<F, Req, router_types::PaymentsResponseData>, bool)>
where
F: Send + Clone + Sync,
Req: Send + Sync,
- router_types::RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
+ RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
@@ -2398,91 +2403,6 @@ pub enum CallConnectorAction {
HandleResponse(Vec<u8>),
}
-pub mod payment_address {
- use super::*;
-
- #[derive(Clone, Default, Debug)]
- pub struct PaymentAddress {
- shipping: Option<api::Address>,
- billing: Option<api::Address>,
- unified_payment_method_billing: Option<api::Address>,
- payment_method_billing: Option<api::Address>,
- }
-
- impl PaymentAddress {
- pub fn new(
- shipping: Option<api::Address>,
- billing: Option<api::Address>,
- payment_method_billing: Option<api::Address>,
- should_unify_address: Option<bool>,
- ) -> Self {
- // billing -> .billing, this is the billing details passed in the root of payments request
- // payment_method_billing -> payment_method_data.billing
-
- let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
- // Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
- // The unified payment_method_billing will be used as billing address and passed to the connector module
- // This unification is required in order to provide backwards compatibility
- // so that if `payment.billing` is passed it should be sent to the connector module
- // Unify the billing details with `payment_method_data.billing`
- payment_method_billing
- .as_ref()
- .map(|payment_method_billing| {
- payment_method_billing
- .clone()
- .unify_address(billing.as_ref())
- })
- .or(billing.clone())
- } else {
- payment_method_billing.clone()
- };
-
- Self {
- shipping,
- billing,
- unified_payment_method_billing,
- payment_method_billing,
- }
- }
-
- pub fn get_shipping(&self) -> Option<&api::Address> {
- self.shipping.as_ref()
- }
-
- pub fn get_payment_method_billing(&self) -> Option<&api::Address> {
- self.unified_payment_method_billing.as_ref()
- }
-
- /// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
- pub fn unify_with_payment_method_data_billing(
- self,
- payment_method_data_billing: Option<api::Address>,
- ) -> Self {
- // Unify the billing details with `payment_method_data.billing_details`
- let unified_payment_method_billing = payment_method_data_billing
- .map(|payment_method_data_billing| {
- payment_method_data_billing.unify_address(self.get_payment_method_billing())
- })
- .or(self.get_payment_method_billing().cloned());
-
- Self {
- shipping: self.shipping,
- billing: self.billing,
- unified_payment_method_billing,
- payment_method_billing: self.payment_method_billing,
- }
- }
-
- pub fn get_request_payment_method_billing(&self) -> Option<&api::Address> {
- self.payment_method_billing.as_ref()
- }
-
- pub fn get_payment_billing(&self) -> Option<&api::Address> {
- self.billing.as_ref()
- }
- }
-}
-
#[derive(Clone)]
pub struct MandateConnectorDetails {
pub connector: String,
@@ -2520,7 +2440,8 @@ where
pub creds_identifier: Option<String>,
pub pm_token: Option<String>,
pub connector_customer_id: Option<String>,
- pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
+ pub recurring_mandate_payment_data:
+ Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>,
pub ephemeral_key: Option<ephemeral_key::EphemeralKey>,
pub redirect_response: Option<api_models::payments::RedirectResponse>,
pub surcharge_details: Option<types::SurchargeDetails>,
@@ -2568,13 +2489,6 @@ pub struct IncrementalAuthorizationDetails {
pub authorization_id: Option<String>,
}
-#[derive(Debug, Default, Clone)]
-pub struct RecurringMandatePaymentData {
- pub payment_method_type: Option<storage_enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
- pub original_payment_authorized_amount: Option<i64>,
- pub original_payment_authorized_currency: Option<storage_enums::Currency>,
-}
-
#[derive(Debug, Default, Clone)]
pub struct CustomerDetails {
pub customer_id: Option<String>,
@@ -3506,7 +3420,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
},
));
payment_data.recurring_mandate_payment_data =
- Some(RecurringMandatePaymentData {
+ Some(hyperswitch_domain_models::router_data::RecurringMandatePaymentData {
payment_method_type: mandate_reference_record
.payment_method_type,
original_payment_authorized_amount: mandate_reference_record
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index a770454b204..75bbb5bda8c 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -212,7 +212,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
}
}
-impl types::PaymentsAuthorizeRouterData {
+pub trait RouterDataAuthorize {
+ fn decide_authentication_type(&mut self);
+
+ /// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
+ fn should_proceed_with_authorize(&self) -> bool;
+}
+
+impl RouterDataAuthorize for types::PaymentsAuthorizeRouterData {
fn decide_authentication_type(&mut self) {
if self.auth_type == diesel_models::enums::AuthenticationType::ThreeDs
&& !self.request.enrolled_for_3ds
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index d1e2e4b0abe..51627e2d68b 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -145,9 +145,31 @@ impl Feature<api::PSync, types::PaymentsSyncData>
}
}
-impl types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> {
+#[async_trait]
+pub trait RouterDataPSync
+where
+ Self: Sized,
+{
async fn execute_connector_processing_step_for_each_capture(
- mut self,
+ &self,
+ _state: &AppState,
+ _pending_connector_capture_id_list: Vec<String>,
+ _call_connector_action: payments::CallConnectorAction,
+ _connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ api::PSync,
+ types::PaymentsSyncData,
+ types::PaymentsResponseData,
+ >,
+ ) -> RouterResult<Self>;
+}
+
+#[async_trait]
+impl RouterDataPSync
+ for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+{
+ async fn execute_connector_processing_step_for_each_capture(
+ &self,
state: &AppState,
pending_connector_capture_id_list: Vec<String>,
call_connector_action: payments::CallConnectorAction,
@@ -164,7 +186,7 @@ impl types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsRespo
let resp = services::execute_connector_processing_step(
state,
connector_integration.clone(),
- &self,
+ self,
call_connector_action.clone(),
None,
)
@@ -174,12 +196,15 @@ impl types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsRespo
} else {
// in trigger, call connector for every capture_id
for connector_capture_id in pending_connector_capture_id_list {
- self.request.connector_transaction_id =
+ // TEMPORARY FIX: remove the clone on router data after removing this function as an impl on trait RouterDataPSync
+ // TRACKING ISSUE: https://github.com/juspay/hyperswitch/issues/4644
+ let mut cloned_router_data = self.clone();
+ cloned_router_data.request.connector_transaction_id =
types::ResponseId::ConnectorTransactionId(connector_capture_id.clone());
let resp = services::execute_connector_processing_step(
state,
connector_integration.clone(),
- &self,
+ &cloned_router_data,
call_connector_action.clone(),
None,
)
@@ -201,10 +226,12 @@ impl types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsRespo
_ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::MultipleCaptureResponse for payment sync".into() })?,
};
}
- self.response = Ok(types::PaymentsResponseData::MultipleCaptureResponse {
- capture_sync_response_list: capture_sync_response_map,
- });
- Ok(self)
+ let mut cloned_router_data = self.clone();
+ cloned_router_data.response =
+ Ok(types::PaymentsResponseData::MultipleCaptureResponse {
+ capture_sync_response_list: capture_sync_response_map,
+ });
+ Ok(cloned_router_data)
}
}
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index e0837be2512..2eb0c921bbf 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -642,8 +642,24 @@ fn log_session_response_if_error(
.map(|res| res.as_ref().map_err(|error| logger::error!(?error)));
}
-impl types::PaymentsSessionRouterData {
- pub async fn decide_flow<'a, 'b>(
+#[async_trait]
+pub trait RouterDataSession
+where
+ Self: Sized,
+{
+ async fn decide_flow<'a, 'b>(
+ &'b self,
+ state: &'a routes::AppState,
+ connector: &api::ConnectorData,
+ _confirm: Option<bool>,
+ call_connector_action: payments::CallConnectorAction,
+ business_profile: &storage::business_profile::BusinessProfile,
+ ) -> RouterResult<Self>;
+}
+
+#[async_trait]
+impl RouterDataSession for types::PaymentsSessionRouterData {
+ async fn decide_flow<'a, 'b>(
&'b self,
state: &'a routes::AppState,
connector: &api::ConnectorData,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index b4b1b09c3fc..5723c7f8b9a 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -48,7 +48,6 @@ use crate::{
routes::{metrics, payment_methods as payment_methods_handler, AppState},
services,
types::{
- self as core_types,
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{
self,
@@ -58,7 +57,8 @@ use crate::{
self, enums as storage_enums, ephemeral_key, CardTokenData, CustomerUpdate::Update,
},
transformers::{ForeignFrom, ForeignTryFrom},
- ErrorResponse, MandateReference, RouterData,
+ AdditionalPaymentMethodConnectorResponse, ErrorResponse, MandateReference,
+ RecurringMandatePaymentData, RouterData,
},
utils::{
self,
@@ -665,7 +665,7 @@ pub async fn get_token_for_recurring_mandate(
Ok(MandateGenericData {
token: Some(token),
payment_method: payment_method.payment_method,
- recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
+ recurring_mandate_payment_data: Some(RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
@@ -679,7 +679,7 @@ pub async fn get_token_for_recurring_mandate(
Ok(MandateGenericData {
token: None,
payment_method: payment_method.payment_method,
- recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
+ recurring_mandate_payment_data: Some(RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
@@ -4198,7 +4198,7 @@ pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErr
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
- connector_response_payment_method_data: core_types::AdditionalPaymentMethodConnectorResponse,
+ connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
match (
&additional_payment_data,
@@ -4206,7 +4206,7 @@ pub fn add_connector_response_to_additional_payment_data(
) {
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
- core_types::AdditionalPaymentMethodConnectorResponse::Card {
+ AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
},
@@ -4223,7 +4223,7 @@ pub fn add_connector_response_to_additional_payment_data(
pub fn update_additional_payment_data_with_connector_response_pm_data(
additional_payment_data: Option<serde_json::Value>,
- connector_response_pm_data: Option<core_types::AdditionalPaymentMethodConnectorResponse>,
+ connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>,
) -> RouterResult<Option<serde_json::Value>> {
let parsed_additional_payment_method_data = additional_payment_data
.as_ref()
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index d41bfcf66d4..081dac14df0 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -111,7 +111,7 @@ where
.to_owned()
.get_required_value("payment_token")?;
let token = match tokens {
- types::PaymentMethodToken::Token(connector_token) => connector_token,
+ types::PaymentMethodToken::Token(connector_token) => connector_token.expose(),
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Apple Pay Decrypt token is not supported".to_string(),
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 41ce77a4de0..42d30da766a 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -7,7 +7,7 @@ use common_enums::RequestIncrementalAuthorization;
use common_utils::{consts::X_HS_LATENCY, fp_utils};
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
-use masking::Maskable;
+use masking::{Maskable, Secret};
use router_env::{instrument, tracing};
use super::{flows::Feature, types::AuthenticationData, PaymentData};
@@ -156,7 +156,9 @@ where
session_token: None,
reference_id: None,
payment_method_status: payment_data.payment_method_info.map(|info| info.status),
- payment_method_token: payment_data.pm_token.map(types::PaymentMethodToken::Token),
+ payment_method_token: payment_data
+ .pm_token
+ .map(|token| types::PaymentMethodToken::Token(Secret::new(token))),
connector_customer: payment_data.connector_customer_id,
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 6f0d0998968..65715464481 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -8,13 +8,14 @@ use common_enums::{IntentStatus, RequestIncrementalAuthorization};
use common_utils::{crypto::Encryptable, pii::Email};
use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{payment_address::PaymentAddress, router_data::ErrorResponse};
#[cfg(feature = "payouts")]
use masking::PeekInterface;
use maud::{html, PreEscaped};
use router_env::{instrument, tracing};
use uuid::Uuid;
-use super::payments::{helpers, PaymentAddress};
+use super::payments::helpers;
#[cfg(feature = "payouts")]
use super::payouts::PayoutData;
#[cfg(feature = "payouts")]
@@ -28,7 +29,7 @@ use crate::{
types::{
self, domain,
storage::{self, enums},
- ErrorResponse, PollConfig,
+ PollConfig,
},
utils::{generate_id, generate_uuid, OptionExt, ValueExt},
};
diff --git a/crates/router/src/core/verify_connector.rs b/crates/router/src/core/verify_connector.rs
index 17cedd1e2d0..8a8b0a14f7d 100644
--- a/crates/router/src/core/verify_connector.rs
+++ b/crates/router/src/core/verify_connector.rs
@@ -6,8 +6,11 @@ use crate::{
core::errors,
services,
types::{
- api,
- api::verify_connector::{self as types, VerifyConnector},
+ api::{
+ self,
+ verify_connector::{self as types, VerifyConnector},
+ },
+ transformers::ForeignInto,
},
utils::verify_connector as utils,
AppState,
@@ -38,7 +41,7 @@ pub async fn verify_connector_credentials(
&state,
types::VerifyConnectorData {
connector: *boxed_connector.connector,
- connector_auth: req.connector_account_details.into(),
+ connector_auth: req.connector_account_details.foreign_into(),
card_details,
},
)
@@ -48,7 +51,7 @@ pub async fn verify_connector_credentials(
&state,
types::VerifyConnectorData {
connector: *boxed_connector.connector,
- connector_auth: req.connector_account_details.into(),
+ connector_auth: req.connector_account_details.foreign_into(),
card_details,
},
)
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index bffa3eaf8f8..886e7c65fd1 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -26,11 +26,19 @@ pub use common_utils::request::RequestContent;
use common_utils::{pii, pii::Email};
use error_stack::ResultExt;
use hyperswitch_domain_models::mandates::{CustomerAcceptance, MandateData};
+pub use hyperswitch_domain_models::{
+ payment_address::PaymentAddress,
+ router_data::{
+ AccessToken, AdditionalPaymentMethodConnectorResponse, ApplePayCryptogramData,
+ ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse,
+ PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData,
+ },
+};
use masking::Secret;
use serde::Serialize;
use self::storage::enums as storage_enums;
-pub use crate::core::payments::{payment_address::PaymentAddress, CustomerDetails};
+pub use crate::core::payments::CustomerDetails;
#[cfg(feature = "payouts")]
use crate::{
connector::utils::missing_field_err,
@@ -40,7 +48,7 @@ use crate::{
consts,
core::{
errors::{self},
- payments::{types, PaymentData, RecurringMandatePaymentData},
+ payments::{types, PaymentData},
},
services,
types::{transformers::ForeignFrom, types::AuthenticationData},
@@ -267,125 +275,6 @@ pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
-#[derive(Debug, Clone)]
-pub struct RouterData<Flow, Request, Response> {
- pub flow: PhantomData<Flow>,
- pub merchant_id: String,
- pub customer_id: Option<String>,
- pub connector_customer: Option<String>,
- pub connector: String,
- pub payment_id: String,
- pub attempt_id: String,
- pub status: storage_enums::AttemptStatus,
- pub payment_method: storage_enums::PaymentMethod,
- pub connector_auth_type: ConnectorAuthType,
- pub description: Option<String>,
- pub return_url: Option<String>,
- pub address: PaymentAddress,
- pub auth_type: storage_enums::AuthenticationType,
- pub connector_meta_data: Option<pii::SecretSerdeValue>,
- pub amount_captured: Option<i64>,
- pub access_token: Option<AccessToken>,
- pub session_token: Option<String>,
- pub reference_id: Option<String>,
- pub payment_method_token: Option<PaymentMethodToken>,
- pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
- pub preprocessing_id: Option<String>,
- /// This is the balance amount for gift cards or voucher
- pub payment_method_balance: Option<PaymentMethodBalance>,
-
- ///for switching between two different versions of the same connector
- pub connector_api_version: Option<String>,
-
- /// Contains flow-specific data required to construct a request and send it to the connector.
- pub request: Request,
-
- /// Contains flow-specific data that the connector responds with.
- pub response: Result<Response, ErrorResponse>,
-
- /// Contains a reference ID that should be sent in the connector request
- pub connector_request_reference_id: String,
-
- #[cfg(feature = "payouts")]
- /// Contains payout method data
- pub payout_method_data: Option<api::PayoutMethodData>,
-
- #[cfg(feature = "payouts")]
- /// Contains payout's quote ID
- pub quote_id: Option<String>,
-
- pub test_mode: Option<bool>,
- pub connector_http_status_code: Option<u16>,
- pub external_latency: Option<u128>,
- /// Contains apple pay flow type simplified or manual
- pub apple_pay_flow: Option<storage_enums::ApplePayFlow>,
-
- pub frm_metadata: Option<serde_json::Value>,
-
- pub dispute_id: Option<String>,
- pub refund_id: Option<String>,
-
- /// This field is used to store various data regarding the response from connector
- pub connector_response: Option<ConnectorResponseData>,
- pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
-}
-
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub enum AdditionalPaymentMethodConnectorResponse {
- Card {
- /// Details regarding the authentication details of the connector, if this is a 3ds payment.
- authentication_data: Option<serde_json::Value>,
- /// Various payment checks that are done for a payment
- payment_checks: Option<serde_json::Value>,
- },
-}
-
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct ConnectorResponseData {
- pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
-}
-
-impl ConnectorResponseData {
- pub fn with_additional_payment_method_data(
- additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
- ) -> Self {
- Self {
- additional_payment_method_data: Some(additional_payment_method_data),
- }
- }
-}
-
-#[derive(Debug, Clone, serde::Deserialize)]
-pub enum PaymentMethodToken {
- Token(String),
- ApplePayDecrypt(Box<ApplePayPredecryptData>),
-}
-
-#[derive(Debug, Clone, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ApplePayPredecryptData {
- pub application_primary_account_number: Secret<String>,
- pub application_expiration_date: String,
- pub currency_code: String,
- pub transaction_amount: i64,
- pub device_manufacturer_identifier: Secret<String>,
- pub payment_data_type: Secret<String>,
- pub payment_data: ApplePayCryptogramData,
-}
-
-#[derive(Debug, Clone, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ApplePayCryptogramData {
- pub online_payment_cryptogram: Secret<String>,
- pub eci_indicator: Option<String>,
-}
-
-#[derive(Debug, Clone)]
-pub struct PaymentMethodBalance {
- pub amount: i64,
- pub currency: storage_enums::Currency,
-}
-
#[cfg(feature = "payouts")]
#[derive(Debug, Clone)]
pub struct PayoutsData {
@@ -876,12 +765,6 @@ pub struct AddAccessTokenResult {
pub connector_supports_access_token: bool,
}
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
-pub struct AccessToken {
- pub token: Secret<String>,
- pub expires: i64,
-}
-
#[derive(serde::Serialize, Debug, Clone)]
pub struct MandateReference {
pub connector_mandate_id: Option<String>,
@@ -1225,42 +1108,8 @@ pub struct MandateRevokeResponseData {
pub mandate_status: MandateStatus,
}
-// Different patterns of authentication.
-#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
-#[serde(tag = "auth_type")]
-pub enum ConnectorAuthType {
- TemporaryAuth,
- HeaderKey {
- api_key: Secret<String>,
- },
- BodyKey {
- api_key: Secret<String>,
- key1: Secret<String>,
- },
- SignatureKey {
- api_key: Secret<String>,
- key1: Secret<String>,
- api_secret: Secret<String>,
- },
- MultiAuthKey {
- api_key: Secret<String>,
- key1: Secret<String>,
- api_secret: Secret<String>,
- key2: Secret<String>,
- },
- CurrencyAuthKey {
- auth_key_map: HashMap<storage_enums::Currency, pii::SecretSerdeValue>,
- },
- CertificateAuth {
- certificate: Secret<String>,
- private_key: Secret<String>,
- },
- #[default]
- NoKey,
-}
-
-impl From<api_models::admin::ConnectorAuthType> for ConnectorAuthType {
- fn from(value: api_models::admin::ConnectorAuthType) -> Self {
+impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType {
+ fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self {
match value {
api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth,
api_models::admin::ConnectorAuthType::HeaderKey { api_key } => {
@@ -1357,35 +1206,6 @@ pub struct Response {
pub status_code: u16,
}
-#[derive(Clone, Debug, serde::Serialize)]
-pub struct ErrorResponse {
- pub code: String,
- pub message: String,
- pub reason: Option<String>,
- pub status_code: u16,
- pub attempt_status: Option<storage_enums::AttemptStatus>,
- pub connector_transaction_id: Option<String>,
-}
-
-impl ErrorResponse {
- pub fn get_not_implemented() -> Self {
- Self {
- code: errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Default,
- }
- .error_code(),
- message: errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Default,
- }
- .error_message(),
- reason: None,
- status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
- attempt_status: None,
- connector_transaction_id: None,
- }
- }
-}
-
impl TryFrom<ConnectorAuthType> for AccessTokenRequestData {
type Error = errors::ApiErrorResponse;
fn try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
@@ -1430,12 +1250,6 @@ impl From<errors::ApiErrorResponse> for ErrorResponse {
}
}
-impl Default for ErrorResponse {
- fn default() -> Self {
- Self::from(errors::ApiErrorResponse::InternalServerError)
- }
-}
-
impl From<&&mut PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData {
fn from(data: &&mut PaymentsAuthorizeRouterData) -> Self {
Self {
@@ -1515,10 +1329,10 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData {
}
}
-impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)>
+impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)>
for RouterData<F2, T2, PaymentsResponseData>
{
- fn from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self {
+ fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self {
let data = item.0;
let request = item.1;
Self {
@@ -1568,12 +1382,12 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)>
#[cfg(feature = "payouts")]
impl<F1, F2>
- From<(
+ ForeignFrom<(
&&mut RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
)> for RouterData<F2, PayoutsData, PayoutsResponseData>
{
- fn from(
+ fn foreign_from(
item: (
&&mut RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index c19fdb26ad6..cd1a44a7022 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -529,9 +529,10 @@ pub trait ConnectorActions: Connector {
access_token: info.clone().and_then(|a| a.access_token),
session_token: None,
reference_id: None,
- payment_method_token: info
- .clone()
- .and_then(|a| a.payment_method_token.map(types::PaymentMethodToken::Token)),
+ payment_method_token: info.clone().and_then(|a| {
+ a.payment_method_token
+ .map(|token| types::PaymentMethodToken::Token(Secret::new(token)))
+ }),
connector_customer: info.clone().and_then(|a| a.connector_customer),
recurring_mandate_payment_data: None,
|
2024-05-02T13:10:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
RouterData moved to crate `hyperswitch_domain_models`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4514
https://github.com/juspay/hyperswitch/issues/4523
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Basic testing is required for all the production connectors(and payment methods) on sandbox.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
650f3fa25c4130a2148862863ff444d16b41d2f3
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4497
|
Bug: refactor: use single purpose token and auth for accept invite
- use single purpose JWT auth and single purpose token for accept invite
- remove user without merchant JWT auth and user auth token
|
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b8399251530..3f913b88a3f 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -170,7 +170,7 @@ pub async fn transfer_org_ownership(
pub async fn accept_invitation(
state: AppState,
- user_token: auth::UserWithoutMerchantFromToken,
+ user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::AcceptInvitationRequest,
_req_state: ReqState,
) -> UserResponse<user_api::DashboardEntryResponse> {
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 7ffcc8d09df..7247c858f4d 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -214,7 +214,7 @@ pub async fn accept_invitation(
&req,
payload,
user_role_core::accept_invitation,
- &auth::UserWithoutMerchantJWTAuth,
+ &auth::SinglePurposeJWTAuth(auth::Purpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 8652f51451a..c49ad81d919 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -149,28 +149,6 @@ impl SinglePurposeToken {
}
}
-// TODO: This has to be removed once single purpose token is used as a intermediate token
-#[derive(Clone, Debug)]
-pub struct UserWithoutMerchantFromToken {
- pub user_id: String,
-}
-
-#[derive(serde::Serialize, serde::Deserialize)]
-pub struct UserAuthToken {
- pub user_id: String,
- pub exp: u64,
-}
-
-#[cfg(feature = "olap")]
-impl UserAuthToken {
- pub async fn new_token(user_id: String, settings: &Settings) -> UserResult<String> {
- let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
- let exp = jwt::generate_exp(exp_duration)?.as_secs();
- let token_payload = Self { user_id, exp };
- jwt::generate_jwt(&token_payload, settings).await
- }
-}
-
#[derive(serde::Serialize, serde::Deserialize)]
pub struct AuthToken {
pub user_id: String,
@@ -330,37 +308,6 @@ where
}
}
-#[derive(Debug)]
-pub struct UserWithoutMerchantJWTAuth;
-
-#[cfg(feature = "olap")]
-#[async_trait]
-impl<A> AuthenticateAndFetch<UserWithoutMerchantFromToken, A> for UserWithoutMerchantJWTAuth
-where
- A: AppStateInfo + Sync,
-{
- async fn authenticate_and_fetch(
- &self,
- request_headers: &HeaderMap,
- state: &A,
- ) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> {
- let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?;
- if payload.check_in_blacklist(state).await? {
- return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
- }
-
- Ok((
- UserWithoutMerchantFromToken {
- user_id: payload.user_id.clone(),
- },
- AuthenticationType::UserJwt {
- user_id: payload.user_id,
- },
- ))
- }
-}
-
-#[allow(dead_code)]
#[derive(Debug)]
pub(crate) struct SinglePurposeJWTAuth(pub Purpose);
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index b2f63f4927e..bc11ee19089 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -5,7 +5,7 @@ use common_utils::date_time;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
-use super::{AuthToken, SinglePurposeToken, UserAuthToken};
+use super::{AuthToken, SinglePurposeToken};
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
@@ -154,16 +154,6 @@ impl BlackList for AuthToken {
}
}
-#[async_trait::async_trait]
-impl BlackList for UserAuthToken {
- async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
- where
- A: AppStateInfo + Sync,
- {
- check_user_in_blacklist(state, &self.user_id, self.exp).await
- }
-}
-
#[async_trait::async_trait]
impl BlackList for SinglePurposeToken {
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 46f8e1340e5..fab02df88ba 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -910,8 +910,9 @@ impl SignInWithMultipleRolesStrategy {
user_api::MerchantSelectResponse {
name: self.user.get_name(),
email: self.user.get_email(),
- token: auth::UserAuthToken::new_token(
+ token: auth::SinglePurposeToken::new_token(
self.user.get_user_id().to_string(),
+ auth::Purpose::AcceptInvite,
&state.conf,
)
.await?
|
2024-04-29T18:57:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- Use single purpose JWT auth and single purpose token for accept invite
- Remove user without merchant JWT auth and user auth token
### 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 [#4497](https://github.com/juspay/hyperswitch/issues/4497)
## How did you test it?
- Enable email feature flag
- Signup/ singin
- Invite a new user from multiple accounts
- Sign in to newly created user
- The response should be merchant select, then do accept invite, it will give dashboard entry response.
<img width="1267" alt="Screenshot 2024-04-29 at 9 23 52 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/190180a5-732c-484b-8ab0-420e96060c9d">
Current and expected behaviour of accept invite should remain same!
```curl
curl --location 'http://localhost:8080/user/user/invite/accept' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_ids": [
"merchant_id1",
"merchant_id2",
"merchant_id3"
],
"need_dashboard_entry_response": true
}'
```
If any of the `merchant_id` status is `active`, then you will be getting the following response.
```
{
"token": "JWT with merchant_id, user_id, user_role",
"merchant_id": "merchant_id",
"name": "user name",
"email": "user email",
"verification_days_left": null,
"user_role": "user role"
}
```
If `need_dashboard_entry_response` is `false` or not sent, then the response will be 200 OK.
## Checklist
<!-- Put an `x` in 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
|
c20ecb855aa3c4b3ce1798dcc19910fb38345b46
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4515
|
Bug: [FEATURE] Rename crate data_models to hyperswitch_domain_models
### Feature Description
Crate `data_models` needs to be renamed to `hyperswitch_domain_models`
### Possible Implementation
Rename crate `data_models` to `hyperswitch_domain_models` and update it's references in entire codebase.
### 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 635edcc995e..00c491d7101 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -337,11 +337,11 @@ dependencies = [
"aws-smithy-types 1.1.8",
"bigdecimal",
"common_utils",
- "data_models",
"diesel_models",
"error-stack",
"external_services",
"futures 0.3.30",
+ "hyperswitch_domain_models",
"hyperswitch_interfaces",
"masking",
"once_cell",
@@ -2402,23 +2402,6 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e962a19be5cfc3f3bf6dd8f61eb50107f356ad6270fbb3ed41476571db78be5"
-[[package]]
-name = "data_models"
-version = "0.1.0"
-dependencies = [
- "api_models",
- "async-trait",
- "common_enums",
- "common_utils",
- "diesel_models",
- "error-stack",
- "masking",
- "serde",
- "serde_json",
- "thiserror",
- "time",
-]
-
[[package]]
name = "deadpool"
version = "0.10.0"
@@ -3619,6 +3602,23 @@ dependencies = [
"tokio 1.37.0",
]
+[[package]]
+name = "hyperswitch_domain_models"
+version = "0.1.0"
+dependencies = [
+ "api_models",
+ "async-trait",
+ "common_enums",
+ "common_utils",
+ "diesel_models",
+ "error-stack",
+ "masking",
+ "serde",
+ "serde_json",
+ "thiserror",
+ "time",
+]
+
[[package]]
name = "hyperswitch_interfaces"
version = "0.1.0"
@@ -5593,7 +5593,6 @@ dependencies = [
"config",
"cookie 0.18.1",
"currency_conversion",
- "data_models",
"derive_deref",
"diesel",
"diesel_models",
@@ -5609,6 +5608,7 @@ dependencies = [
"hex",
"http 0.2.12",
"hyper 0.14.28",
+ "hyperswitch_domain_models",
"hyperswitch_interfaces",
"image",
"infer",
@@ -6643,13 +6643,13 @@ dependencies = [
"common_utils",
"config",
"crc32fast",
- "data_models",
"diesel",
"diesel_models",
"dyn-clone",
"error-stack",
"futures 0.3.30",
"http 0.2.12",
+ "hyperswitch_domain_models",
"masking",
"mime",
"moka",
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index b6cd29badee..52680df5c49 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -26,7 +26,7 @@ router_env = { version = "0.1.0", path = "../router_env", features = [
diesel_models = { version = "0.1.0", path = "../diesel_models", features = [
"kv_store",
] }
-data_models = { version = "0.1.0", path = "../data_models", default-features = false }
+hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
#Third Party dependencies
actix-web = "4.5.1"
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 58569338cf6..7b19ba0ed06 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -4,8 +4,8 @@ use api_models::{
};
use aws_config::{self, meta::region::RegionProviderChain, Region};
use common_utils::errors::{CustomResult, ErrorSwitch};
-use data_models::errors::{StorageError, StorageResult};
use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::{StorageError, StorageResult};
use opensearch::{
auth::Credentials,
cert::CertificateValidation,
diff --git a/crates/data_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
similarity index 96%
rename from crates/data_models/Cargo.toml
rename to crates/hyperswitch_domain_models/Cargo.toml
index 54130ca002a..58eff10a363 100644
--- a/crates/data_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "data_models"
+name = "hyperswitch_domain_models"
description = "Represents the data/domain models used by the business layer"
version = "0.1.0"
edition.workspace = true
diff --git a/crates/data_models/README.md b/crates/hyperswitch_domain_models/README.md
similarity index 70%
rename from crates/data_models/README.md
rename to crates/hyperswitch_domain_models/README.md
index 0c1c5170558..d0b974d13c6 100644
--- a/crates/data_models/README.md
+++ b/crates/hyperswitch_domain_models/README.md
@@ -1,3 +1,3 @@
-# Data models
+# Hyperswitch domain models
Represents the data/domain models used by the business/domain layer
\ No newline at end of file
diff --git a/crates/data_models/src/errors.rs b/crates/hyperswitch_domain_models/src/errors.rs
similarity index 100%
rename from crates/data_models/src/errors.rs
rename to crates/hyperswitch_domain_models/src/errors.rs
diff --git a/crates/data_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
similarity index 100%
rename from crates/data_models/src/lib.rs
rename to crates/hyperswitch_domain_models/src/lib.rs
diff --git a/crates/data_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs
similarity index 100%
rename from crates/data_models/src/mandates.rs
rename to crates/hyperswitch_domain_models/src/mandates.rs
diff --git a/crates/data_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
similarity index 100%
rename from crates/data_models/src/payments.rs
rename to crates/hyperswitch_domain_models/src/payments.rs
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
similarity index 100%
rename from crates/data_models/src/payments/payment_attempt.rs
rename to crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
similarity index 100%
rename from crates/data_models/src/payments/payment_intent.rs
rename to crates/hyperswitch_domain_models/src/payments/payment_intent.rs
diff --git a/crates/data_models/src/payouts.rs b/crates/hyperswitch_domain_models/src/payouts.rs
similarity index 100%
rename from crates/data_models/src/payouts.rs
rename to crates/hyperswitch_domain_models/src/payouts.rs
diff --git a/crates/data_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
similarity index 100%
rename from crates/data_models/src/payouts/payout_attempt.rs
rename to crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
diff --git a/crates/data_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
similarity index 100%
rename from crates/data_models/src/payouts/payouts.rs
rename to crates/hyperswitch_domain_models/src/payouts/payouts.rs
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 8915ab573e0..f8e2cfad126 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -14,7 +14,7 @@ email = ["external_services/email", "scheduler/email", "olap"]
frm = ["api_models/frm"]
stripe = ["dep:serde_qs"]
release = ["stripe", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3"]
-olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
+olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
oltp = ["storage_impl/oltp"]
kv_store = ["scheduler/kv_store"]
accounts_cache = []
@@ -26,7 +26,7 @@ dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "kgra
connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"]
external_access_dc = ["dummy_connector"]
detailed_errors = ["api_models/detailed_errors", "error-stack/serde"]
-payouts = ["api_models/payouts", "common_enums/payouts", "data_models/payouts", "storage_impl/payouts"]
+payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts"]
payout_retry = ["payouts"]
recon = ["email", "api_models/recon"]
retry = []
@@ -104,7 +104,7 @@ cards = { version = "0.1.0", path = "../cards" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs"] }
currency_conversion = { version = "0.1.0", path = "../currency_conversion" }
-data_models = { version = "0.1.0", path = "../data_models", default-features = false }
+hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] }
pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" }
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index a240154a0f3..8fd148864f5 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -373,11 +373,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
.get_setup_mandate_details()
.map(|mandate_data| {
let max_amount = match &mandate_data.mandate_type {
- Some(data_models::mandates::MandateDataType::SingleUse(mandate))
- | Some(data_models::mandates::MandateDataType::MultiUse(Some(mandate))) => {
- conn_utils::to_currency_base_unit(mandate.amount, mandate.currency)
- }
- Some(data_models::mandates::MandateDataType::MultiUse(None)) => {
+ Some(hyperswitch_domain_models::mandates::MandateDataType::SingleUse(
+ mandate,
+ ))
+ | Some(hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(
+ mandate,
+ ))) => conn_utils::to_currency_base_unit(mandate.amount, mandate.currency),
+ Some(hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None)) => {
Err(errors::ConnectorError::MissingRequiredField {
field_name:
"setup_future_usage.mandate_data.mandate_type.multi_use.amount",
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 793ec2d87db..e0d7a58566d 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -5,8 +5,8 @@ use common_utils::{
fp_utils,
pii::{Email, IpAddress},
};
-use data_models::mandates::MandateDataType;
use error_stack::ResultExt;
+use hyperswitch_domain_models::mandates::MandateDataType;
use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 093a319f870..46c47a51f32 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -7,8 +7,8 @@ use common_utils::{
pii::{self, Email},
request::RequestContent,
};
-use data_models::mandates::AcceptanceType;
use error_stack::ResultExt;
+use hyperswitch_domain_models::mandates::AcceptanceType;
use masking::{ExposeInterface, ExposeOptionInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index efcaa5bfce7..2cb3aa436e4 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -12,9 +12,9 @@ use common_utils::{
errors::ReportSwitchExt,
pii::{self, Email, IpAddress},
};
-use data_models::payments::payment_attempt::PaymentAttempt;
use diesel_models::enums;
use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use masking::{ExposeInterface, Secret};
use once_cell::sync::Lazy;
use regex::Regex;
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index a7d36ff5128..d80d86460b2 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -10,8 +10,8 @@ use std::fmt::Display;
use actix_web::{body::BoxBody, ResponseError};
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
-pub use data_models::errors::StorageError as DataStorageError;
use diesel_models::errors as storage_errors;
+pub use hyperswitch_domain_models::errors::StorageError as DataStorageError;
pub use redis_interface::errors::RedisError;
use scheduler::errors as sch_errors;
use storage_impl::errors as storage_impl_errors;
diff --git a/crates/router/src/core/errors/user/sample_data.rs b/crates/router/src/core/errors/user/sample_data.rs
index 84c6c9fa43a..3e72e49d317 100644
--- a/crates/router/src/core/errors/user/sample_data.rs
+++ b/crates/router/src/core/errors/user/sample_data.rs
@@ -1,6 +1,6 @@
use api_models::errors::types::{ApiError, ApiErrorResponse};
use common_utils::errors::{CustomResult, ErrorSwitch, ErrorSwitchFrom};
-use data_models::errors::StorageError;
+use hyperswitch_domain_models::errors::StorageError;
pub type SampleDataResult<T> = CustomResult<T, SampleDataError>;
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index f664c33681c..678a351a4c3 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -42,7 +42,7 @@ impl<T> StorageErrorExt<T, errors::CustomersErrorResponse>
}
impl<T> StorageErrorExt<T, errors::ApiErrorResponse>
- for error_stack::Result<T, data_models::errors::StorageError>
+ for error_stack::Result<T, hyperswitch_domain_models::errors::StorageError>
{
#[track_caller]
fn to_not_found_response(
@@ -51,8 +51,10 @@ impl<T> StorageErrorExt<T, errors::ApiErrorResponse>
) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
- data_models::errors::StorageError::ValueNotFound(_) => not_found_response,
- data_models::errors::StorageError::CustomerRedacted => {
+ hyperswitch_domain_models::errors::StorageError::ValueNotFound(_) => {
+ not_found_response
+ }
+ hyperswitch_domain_models::errors::StorageError::CustomerRedacted => {
errors::ApiErrorResponse::CustomerRedacted
}
_ => errors::ApiErrorResponse::InternalServerError,
@@ -68,7 +70,9 @@ impl<T> StorageErrorExt<T, errors::ApiErrorResponse>
) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
- data_models::errors::StorageError::DuplicateValue { .. } => duplicate_response,
+ hyperswitch_domain_models::errors::StorageError::DuplicateValue { .. } => {
+ duplicate_response
+ }
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index d59c8c5ff47..3a80865bcd0 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -2,7 +2,7 @@ use api_models::payments::HeaderPayload;
use async_trait::async_trait;
use common_enums::{CaptureMethod, FrmSuggestion};
use common_utils::ext_traits::Encode;
-use data_models::payments::{
+use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttemptUpdate, payment_intent::PaymentIntentUpdate,
};
use router_env::{instrument, logger, tracing};
diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs
index 082210a2e47..5acd722077f 100644
--- a/crates/router/src/core/fraud_check/types.rs
+++ b/crates/router/src/core/fraud_check/types.rs
@@ -6,7 +6,7 @@ use api_models::{
};
use common_enums::FrmSuggestion;
use common_utils::pii::Email;
-use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index 84aa9b48e6f..939367bd4db 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -515,6 +515,8 @@ pub trait MandateBehaviour {
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds>;
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>);
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData;
- fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData>;
+ fn get_setup_mandate_details(
+ &self,
+ ) -> Option<&hyperswitch_domain_models::mandates::MandateData>;
fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>;
}
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index c15969fd1c8..f3b7b384e2d 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -1,9 +1,9 @@
use api_models::payments as api_payments;
use common_enums::enums;
use common_utils::errors::CustomResult;
-use data_models::mandates::MandateData;
use diesel_models::Mandate;
use error_stack::ResultExt;
+use hyperswitch_domain_models::mandates::MandateData;
use crate::{
core::{errors, payments},
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 2b7577e1fb8..b2a4959edfb 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -7,8 +7,8 @@ pub use api_models::enums::Connector;
use api_models::payments::CardToken;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
-use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use diesel_models::enums;
+use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use crate::{
core::{errors::RouterResult, payments::helpers, pm_auth as core_pm_auth},
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 42145550c89..27d126bce90 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2504,7 +2504,7 @@ pub async fn list_payment_methods(
payment_methods: payment_method_responses,
mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map(
|d| match d {
- data_models::mandates::MandateDataType::SingleUse(i) => {
+ hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
@@ -2513,7 +2513,7 @@ pub async fn list_payment_methods(
metadata: i.metadata,
})
}
- data_models::mandates::MandateDataType::MultiUse(Some(i)) => {
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {
api::MandateType::MultiUse(Some(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
@@ -2522,7 +2522,7 @@ pub async fn list_payment_methods(
metadata: i.metadata,
}))
}
- data_models::mandates::MandateDataType::MultiUse(None) => {
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
},
@@ -3190,7 +3190,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
.await
} else {
let cloned_secret = req.and_then(|r| r.client_secret.as_ref().cloned());
- let payment_intent: Option<data_models::payments::PaymentIntent> =
+ let payment_intent: Option<hyperswitch_domain_models::payments::PaymentIntent> =
helpers::verify_payment_intent_time_and_client_secret(
db,
&merchant_account,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e2a5f148440..e69227155a5 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -27,12 +27,12 @@ use common_utils::{
pii,
types::Surcharge,
};
-use data_models::mandates::{CustomerAcceptance, MandateData};
use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
use error_stack::{report, ResultExt};
use events::EventInfo;
use futures::future::join_all;
use helpers::ApplePayData;
+use hyperswitch_domain_models::mandates::{CustomerAcceptance, MandateData};
use masking::{ExposeInterface, Secret};
pub use payment_address::PaymentAddress;
use redis_interface::errors::RedisError;
@@ -2703,7 +2703,7 @@ pub async fn list_payments(
merchant: domain::MerchantAccount,
constraints: api::PaymentListConstraints,
) -> RouterResponse<api::PaymentListResponse> {
- use data_models::errors::StorageError;
+ use hyperswitch_domain_models::errors::StorageError;
helpers::validate_payment_list_request(&constraints)?;
let merchant_id = &merchant.merchant_id;
let db = state.store.as_ref();
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index e44456fb1c7..6b64dc04044 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -231,7 +231,9 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData {
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
- fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> {
+ fn get_setup_mandate_details(
+ &self,
+ ) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 6a810e9b3dd..59f7ee17551 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -177,7 +177,9 @@ impl mandate::MandateBehaviour for types::SetupMandateRequestData {
self.payment_method_data.clone()
}
- fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> {
+ fn get_setup_mandate_details(
+ &self,
+ ) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 45816b875c7..be04d2fb1ac 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -9,13 +9,13 @@ use common_utils::{
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
fp_utils, generate_id, pii,
};
-use data_models::{
- mandates::MandateData,
- payments::{payment_attempt::PaymentAttempt, PaymentIntent},
-};
use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ mandates::MandateData,
+ payments::{payment_attempt::PaymentAttempt, PaymentIntent},
+};
use josekit::jwe;
use masking::{ExposeInterface, PeekInterface};
use openssl::{
@@ -2672,24 +2672,28 @@ pub fn generate_mandate(
Ok(Some(
match data.mandate_type.get_required_value("mandate_type")? {
- data_models::mandates::MandateDataType::SingleUse(data) => new_mandate
- .set_mandate_amount(Some(data.amount))
- .set_mandate_currency(Some(data.currency))
- .set_mandate_type(storage_enums::MandateType::SingleUse)
- .to_owned(),
-
- data_models::mandates::MandateDataType::MultiUse(op_data) => match op_data {
- Some(data) => new_mandate
+ hyperswitch_domain_models::mandates::MandateDataType::SingleUse(data) => {
+ new_mandate
.set_mandate_amount(Some(data.amount))
.set_mandate_currency(Some(data.currency))
- .set_start_date(data.start_date)
- .set_end_date(data.end_date),
- // .set_metadata(data.metadata),
- // we are storing PaymentMethodData in metadata of mandate
- None => &mut new_mandate,
+ .set_mandate_type(storage_enums::MandateType::SingleUse)
+ .to_owned()
+ }
+
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(op_data) => {
+ match op_data {
+ Some(data) => new_mandate
+ .set_mandate_amount(Some(data.amount))
+ .set_mandate_currency(Some(data.currency))
+ .set_start_date(data.start_date)
+ .set_end_date(data.end_date),
+ // .set_metadata(data.metadata),
+ // we are storing PaymentMethodData in metadata of mandate
+ None => &mut new_mandate,
+ }
+ .set_mandate_type(storage_enums::MandateType::MultiUse)
+ .to_owned()
}
- .set_mandate_type(storage_enums::MandateType::MultiUse)
- .to_owned(),
},
))
}
@@ -2911,7 +2915,9 @@ mod tests {
fingerprint_id: None,
off_session: None,
client_secret: Some("1".to_string()),
- active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ "nopes".to_string(),
+ ),
business_country: None,
business_label: None,
order_details: None,
@@ -2967,7 +2973,9 @@ mod tests {
setup_future_usage: None,
off_session: None,
client_secret: Some("1".to_string()),
- active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ "nopes".to_string(),
+ ),
business_country: None,
business_label: None,
order_details: None,
@@ -3022,7 +3030,9 @@ mod tests {
off_session: None,
client_secret: None,
fingerprint_id: None,
- active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ "nopes".to_string(),
+ ),
business_country: None,
business_label: None,
order_details: None,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 7560257ab26..78162fbfa65 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -5,12 +5,12 @@ use api_models::{
};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
-use data_models::{
+use diesel_models::{ephemeral_key, PaymentMethod};
+use error_stack::{self, ResultExt};
+use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
payments::payment_attempt::PaymentAttempt,
};
-use diesel_models::{ephemeral_key, PaymentMethod};
-use error_stack::{self, ResultExt};
use masking::{ExposeInterface, PeekInterface};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
@@ -999,7 +999,9 @@ impl PaymentCreate {
metadata: request.metadata.clone(),
business_country: request.business_country,
business_label: request.business_label.clone(),
- active_attempt: data_models::RemoteStorageObject::ForeignID(active_attempt_id),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ active_attempt_id,
+ ),
order_details,
amount_captured: None,
customer_id: None,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 47d659b5ed2..f4408749fd3 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -3,9 +3,9 @@ use std::collections::HashMap;
use async_trait::async_trait;
use common_enums::AuthorizationStatus;
use common_utils::ext_traits::Encode;
-use data_models::payments::payment_attempt::PaymentAttempt;
use error_stack::{report, ResultExt};
use futures::FutureExt;
+use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use router_derive;
use router_env::{instrument, logger, tracing};
use storage_impl::DataModelExt;
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index e2502e2ecb6..ff7303c900d 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -171,10 +171,10 @@ where
.customer_acceptance
.clone()
.map(|cat| match cat.acceptance_type {
- data_models::mandates::AcceptanceType::Online => {
+ hyperswitch_domain_models::mandates::AcceptanceType::Online => {
euclid_enums::MandateAcceptanceType::Online
}
- data_models::mandates::AcceptanceType::Offline => {
+ hyperswitch_domain_models::mandates::AcceptanceType::Offline => {
euclid_enums::MandateAcceptanceType::Offline
}
})
@@ -184,10 +184,10 @@ where
.as_ref()
.and_then(|mandate_data| {
mandate_data.mandate_type.clone().map(|mt| match mt {
- data_models::mandates::MandateDataType::SingleUse(_) => {
+ hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => {
euclid_enums::MandateType::SingleUse
}
- data_models::mandates::MandateDataType::MultiUse(_) => {
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => {
euclid_enums::MandateType::MultiUse
}
})
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index b891998dae3..d459f632d8f 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -661,10 +661,10 @@ where
customer_acceptance: d.customer_acceptance.map(|d| {
api::CustomerAcceptance {
acceptance_type: match d.acceptance_type {
- data_models::mandates::AcceptanceType::Online => {
+ hyperswitch_domain_models::mandates::AcceptanceType::Online => {
api::AcceptanceType::Online
}
- data_models::mandates::AcceptanceType::Offline => {
+ hyperswitch_domain_models::mandates::AcceptanceType::Offline => {
api::AcceptanceType::Offline
}
},
@@ -676,7 +676,7 @@ where
}
}),
mandate_type: d.mandate_type.map(|d| match d {
- data_models::mandates::MandateDataType::MultiUse(Some(i)) => {
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {
api::MandateType::MultiUse(Some(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
@@ -685,7 +685,7 @@ where
metadata: i.metadata,
}))
}
- data_models::mandates::MandateDataType::SingleUse(i) => {
+ hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::payments::MandateAmountData {
amount: i.amount,
currency: i.currency,
@@ -694,7 +694,7 @@ where
metadata: i.metadata,
})
}
- data_models::mandates::MandateDataType::MultiUse(None) => {
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
}),
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 73825558068..b297470bce8 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -7,9 +7,9 @@ use common_utils::{
ext_traits::{Encode, OptionExt},
types as common_types,
};
-use data_models::payments::payment_attempt::PaymentAttempt;
use diesel_models::business_profile::BusinessProfile;
use error_stack::ResultExt;
+use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index bdaa0c01a10..25f61919207 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -7,12 +7,12 @@ use std::vec::IntoIter;
use api_models::enums as api_enums;
use common_utils::{consts, crypto::Encryptable, ext_traits::ValueExt, pii};
-#[cfg(feature = "olap")]
-use data_models::errors::StorageError;
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
#[cfg(feature = "olap")]
use futures::future::join_all;
+#[cfg(feature = "olap")]
+use hyperswitch_domain_models::errors::StorageError;
#[cfg(feature = "payout_retry")]
use retry::GsmValidation;
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index 02ba3066544..496aab13b13 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -1,7 +1,7 @@
#[cfg(feature = "olap")]
use common_utils::errors::CustomResult;
-pub use data_models::errors::StorageError;
use error_stack::{report, ResultExt};
+pub use hyperswitch_domain_models::errors::StorageError;
use router_env::{instrument, tracing};
use super::helpers;
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 6d5ae7a08c3..09ea935ea76 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -16,9 +16,9 @@ use common_utils::{
ext_traits::AsyncExt,
generate_id,
};
-use data_models::payments::PaymentIntent;
use error_stack::ResultExt;
use helpers::PaymentAuthConnectorDataExt;
+use hyperswitch_domain_models::payments::PaymentIntent;
use masking::{ExposeInterface, PeekInterface, Secret};
use pm_auth::{
connector::plaid::transformers::PlaidAuthType,
diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs
index 43d44ebe41d..49248ae4fea 100644
--- a/crates/router/src/core/refunds/validator.rs
+++ b/crates/router/src/core/refunds/validator.rs
@@ -107,7 +107,7 @@ pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::Api
}
pub fn validate_for_valid_refunds(
- payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt,
+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector: api_models::enums::Connector,
) -> RouterResult<()> {
let payment_method = payment_attempt
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs
index f95f48f19e7..e1bde652305 100644
--- a/crates/router/src/core/user/sample_data.rs
+++ b/crates/router/src/core/user/sample_data.rs
@@ -1,7 +1,7 @@
use api_models::user::sample_data::SampleDataRequest;
use common_utils::errors::ReportSwitchExt;
-use data_models::payments::payment_intent::PaymentIntentNew;
use diesel_models::{user::sample_data::PaymentAttemptBatchNew, RefundNew};
+use hyperswitch_domain_models::payments::payment_intent::PaymentIntentNew;
pub type SampleDataApiResponse<T> = SampleDataResult<ApplicationResponse<T>>;
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index c7a22e56897..3923663f5d1 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -976,7 +976,7 @@ pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
pub fn get_connector_request_reference_id(
conf: &Settings,
merchant_id: &str,
- payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt,
+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
let is_config_enabled_for_merchant =
is_merchant_enabled_for_payment_id_as_connector_request_id(conf, merchant_id);
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index eb6faea5c3b..6647549e399 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -307,8 +307,10 @@ pub async fn get_payment_attempt_from_object_reference_id(
state: &AppState,
object_reference_id: api_models::webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
-) -> CustomResult<data_models::payments::payment_attempt::PaymentAttempt, errors::ApiErrorResponse>
-{
+) -> CustomResult<
+ hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
+ errors::ApiErrorResponse,
+> {
let db = &*state.store;
match object_reference_id {
api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db
@@ -346,7 +348,7 @@ pub async fn get_or_update_dispute_object(
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: api::disputes::DisputePayload,
merchant_id: &str,
- payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt,
+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
event_type: api_models::webhooks::IncomingWebhookEvent,
business_profile: &diesel_models::business_profile::BusinessProfile,
connector_name: &str,
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 9f9e61a5ffc..9b222486d18 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -35,18 +35,20 @@ pub mod routing_algorithm;
pub mod user;
pub mod user_role;
-use data_models::payments::{
- payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface,
-};
-#[cfg(feature = "payouts")]
-use data_models::payouts::{payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface};
-#[cfg(not(feature = "payouts"))]
-use data_models::{PayoutAttemptInterface, PayoutsInterface};
use diesel_models::{
fraud_check::{FraudCheck, FraudCheckNew, FraudCheckUpdate},
organization::{Organization, OrganizationNew, OrganizationUpdate},
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::payments::{
+ payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface,
+};
+#[cfg(feature = "payouts")]
+use hyperswitch_domain_models::payouts::{
+ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
+};
+#[cfg(not(feature = "payouts"))]
+use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::PeekInterface;
use redis_interface::errors::RedisError;
use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, MockDb};
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 34bf7552a48..0aaa47365fc 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2,13 +2,6 @@ use std::sync::Arc;
use common_enums::enums::MerchantStorageScheme;
use common_utils::{errors::CustomResult, pii};
-use data_models::payments::{
- payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface,
-};
-#[cfg(feature = "payouts")]
-use data_models::payouts::{payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface};
-#[cfg(not(feature = "payouts"))]
-use data_models::{PayoutAttemptInterface, PayoutsInterface};
use diesel_models::{
enums,
enums::ProcessTrackerStatus,
@@ -16,6 +9,15 @@ use diesel_models::{
reverse_lookup::{ReverseLookup, ReverseLookupNew},
user_role as user_storage,
};
+use hyperswitch_domain_models::payments::{
+ payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface,
+};
+#[cfg(feature = "payouts")]
+use hyperswitch_domain_models::payouts::{
+ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
+};
+#[cfg(not(feature = "payouts"))]
+use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::Secret;
use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId};
use router_env::logger;
@@ -1238,11 +1240,11 @@ impl PaymentAttemptInterface for KafkaStore {
async fn get_filters_for_payments(
&self,
- pi: &[data_models::payments::PaymentIntent],
+ pi: &[hyperswitch_domain_models::payments::PaymentIntent],
merchant_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
- data_models::payments::payment_attempt::PaymentListFilters,
+ hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
errors::DataStorageError,
> {
self.diesel_store
@@ -1344,7 +1346,7 @@ impl PaymentIntentInterface for KafkaStore {
async fn filter_payment_intent_by_constraints(
&self,
merchant_id: &str,
- filters: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> {
self.diesel_store
@@ -1372,12 +1374,12 @@ impl PaymentIntentInterface for KafkaStore {
async fn get_filtered_payment_intents_attempt(
&self,
merchant_id: &str,
- constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
Vec<(
- data_models::payments::PaymentIntent,
- data_models::payments::payment_attempt::PaymentAttempt,
+ hyperswitch_domain_models::payments::PaymentIntent,
+ hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
)>,
errors::DataStorageError,
> {
@@ -1390,7 +1392,7 @@ impl PaymentIntentInterface for KafkaStore {
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &str,
- constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<String>, errors::DataStorageError> {
self.diesel_store
@@ -1584,11 +1586,11 @@ impl PayoutAttemptInterface for KafkaStore {
async fn get_filters_for_payouts(
&self,
- payouts: &[data_models::payouts::payouts::Payouts],
+ payouts: &[hyperswitch_domain_models::payouts::payouts::Payouts],
merchant_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
- data_models::payouts::payout_attempt::PayoutListFilters,
+ hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters,
errors::DataStorageError,
> {
self.diesel_store
@@ -1663,7 +1665,7 @@ impl PayoutsInterface for KafkaStore {
async fn filter_payouts_by_constraints(
&self,
merchant_id: &str,
- filters: &data_models::payouts::PayoutFetchConstraints,
+ filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {
self.diesel_store
@@ -1675,7 +1677,7 @@ impl PayoutsInterface for KafkaStore {
async fn filter_payouts_and_attempts(
&self,
merchant_id: &str,
- filters: &data_models::payouts::PayoutFetchConstraints,
+ filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
Vec<(
@@ -2482,9 +2484,11 @@ impl DashboardMetadataInterface for KafkaStore {
impl BatchSampleDataInterface for KafkaStore {
async fn insert_payment_intents_batch_for_sample_data(
&self,
- batch: Vec<data_models::payments::payment_intent::PaymentIntentNew>,
- ) -> CustomResult<Vec<data_models::payments::PaymentIntent>, data_models::errors::StorageError>
- {
+ batch: Vec<hyperswitch_domain_models::payments::payment_intent::PaymentIntentNew>,
+ ) -> CustomResult<
+ Vec<hyperswitch_domain_models::payments::PaymentIntent>,
+ hyperswitch_domain_models::errors::StorageError,
+ > {
let payment_intents_list = self
.diesel_store
.insert_payment_intents_batch_for_sample_data(batch)
@@ -2503,8 +2507,8 @@ impl BatchSampleDataInterface for KafkaStore {
&self,
batch: Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>,
) -> CustomResult<
- Vec<data_models::payments::payment_attempt::PaymentAttempt>,
- data_models::errors::StorageError,
+ Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
+ hyperswitch_domain_models::errors::StorageError,
> {
let payment_attempts_list = self
.diesel_store
@@ -2523,7 +2527,8 @@ impl BatchSampleDataInterface for KafkaStore {
async fn insert_refunds_batch_for_sample_data(
&self,
batch: Vec<diesel_models::RefundNew>,
- ) -> CustomResult<Vec<diesel_models::Refund>, data_models::errors::StorageError> {
+ ) -> CustomResult<Vec<diesel_models::Refund>, hyperswitch_domain_models::errors::StorageError>
+ {
let refunds_list = self
.diesel_store
.insert_refunds_batch_for_sample_data(batch)
@@ -2538,8 +2543,10 @@ impl BatchSampleDataInterface for KafkaStore {
async fn delete_payment_intents_for_sample_data(
&self,
merchant_id: &str,
- ) -> CustomResult<Vec<data_models::payments::PaymentIntent>, data_models::errors::StorageError>
- {
+ ) -> CustomResult<
+ Vec<hyperswitch_domain_models::payments::PaymentIntent>,
+ hyperswitch_domain_models::errors::StorageError,
+ > {
let payment_intents_list = self
.diesel_store
.delete_payment_intents_for_sample_data(merchant_id)
@@ -2558,8 +2565,8 @@ impl BatchSampleDataInterface for KafkaStore {
&self,
merchant_id: &str,
) -> CustomResult<
- Vec<data_models::payments::payment_attempt::PaymentAttempt>,
- data_models::errors::StorageError,
+ Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
+ hyperswitch_domain_models::errors::StorageError,
> {
let payment_attempts_list = self
.diesel_store
@@ -2579,7 +2586,8 @@ impl BatchSampleDataInterface for KafkaStore {
async fn delete_refunds_for_sample_data(
&self,
merchant_id: &str,
- ) -> CustomResult<Vec<diesel_models::Refund>, data_models::errors::StorageError> {
+ ) -> CustomResult<Vec<diesel_models::Refund>, hyperswitch_domain_models::errors::StorageError>
+ {
let refunds_list = self
.diesel_store
.delete_refunds_for_sample_data(merchant_id)
diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs
index ae98332cfc4..f7926021afd 100644
--- a/crates/router/src/db/user/sample_data.rs
+++ b/crates/router/src/db/user/sample_data.rs
@@ -1,7 +1,3 @@
-use data_models::{
- errors::StorageError,
- payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntentNew, PaymentIntent},
-};
use diesel_models::{
errors::DatabaseError,
query::user::sample_data as sample_data_queries,
@@ -9,6 +5,10 @@ use diesel_models::{
user::sample_data::PaymentAttemptBatchNew,
};
use error_stack::{Report, ResultExt};
+use hyperswitch_domain_models::{
+ errors::StorageError,
+ payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntentNew, PaymentIntent},
+};
use storage_impl::DataModelExt;
use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store};
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index d226c2bdbed..4bca5824835 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -1,6 +1,6 @@
-use data_models::errors::{StorageError, StorageResult};
use error_stack::ResultExt;
use events::{EventsError, Message, MessagingInterface};
+use hyperswitch_domain_models::errors::{StorageError, StorageResult};
use masking::ErasedMaskSerialize;
use router_env::logger;
use serde::{Deserialize, Serialize};
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 6b604498c71..5af325a46f7 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -13,8 +13,8 @@ pub mod recon;
#[cfg(feature = "email")]
pub mod email;
-use data_models::errors::StorageResult;
use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::StorageResult;
use masking::{ExposeInterface, StrongSecret};
#[cfg(feature = "kv_store")]
use storage_impl::KVRouterStore;
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 3ae923e246f..ba9806b29d1 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -15,8 +15,8 @@ mod dispute;
mod payment_attempt;
mod payment_intent;
mod refund;
-use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use diesel_models::refund::Refund;
+use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use serde::Serialize;
use time::{OffsetDateTime, PrimitiveDateTime};
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index 787a633b0c5..9f442876fab 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -1,6 +1,8 @@
// use diesel_models::enums::MandateDetails;
-use data_models::{mandates::MandateDetails, payments::payment_attempt::PaymentAttempt};
use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::{
+ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
+};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index 6a756c664d4..2edd0d49ccc 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -1,5 +1,5 @@
-use data_models::payments::PaymentIntent;
use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::payments::PaymentIntent;
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs
index e2bd8ef83fd..6b25c724eb8 100644
--- a/crates/router/src/services/kafka/payout.rs
+++ b/crates/router/src/services/kafka/payout.rs
@@ -1,6 +1,6 @@
use common_utils::pii;
-use data_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts};
use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 77d53584dab..bffa3eaf8f8 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -24,8 +24,8 @@ pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
use common_enums::MandateStatus;
pub use common_utils::request::RequestContent;
use common_utils::{pii, pii::Email};
-use data_models::mandates::{CustomerAcceptance, MandateData};
use error_stack::ResultExt;
+use hyperswitch_domain_models::mandates::{CustomerAcceptance, MandateData};
use masking::Secret;
use serde::Serialize;
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 38fd773b9b3..57f51c7b8b0 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -93,7 +93,7 @@ pub trait ConnectorMandateRevoke:
pub trait ConnectorTransactionId: ConnectorCommon + Sync {
fn connector_transaction_id(
&self,
- payment_attempt: data_models::payments::payment_attempt::PaymentAttempt,
+ payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, errors::ApiErrorResponse> {
Ok(payment_attempt.connector_transaction_id)
}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index ec164000b32..77550bedabe 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -39,19 +39,19 @@ pub mod user_role;
use std::collections::HashMap;
-pub use data_models::payments::{
+pub use diesel_models::{
+ ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate,
+};
+pub use hyperswitch_domain_models::payments::{
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
PaymentIntent,
};
#[cfg(feature = "payouts")]
-pub use data_models::payouts::{
+pub use hyperswitch_domain_models::payouts::{
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
payouts::{Payouts, PayoutsNew, PayoutsUpdate},
};
-pub use diesel_models::{
- ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate,
-};
pub use scheduler::db::process_tracker;
pub use self::{
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 0d840326f9b..41e1aae635d 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -1,8 +1,8 @@
-pub use data_models::payments::payment_attempt::{
- PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate,
-};
use diesel_models::{capture::CaptureNew, enums};
use error_stack::ResultExt;
+pub use hyperswitch_domain_models::payments::payment_attempt::{
+ PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate,
+};
use crate::{
core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index ba60da5748d..ef12e32d57c 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -315,30 +315,34 @@ impl ForeignFrom<storage_enums::MandateAmountData> for api_models::payments::Man
}
// TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information
-impl ForeignFrom<api_models::payments::MandateData> for data_models::mandates::MandateData {
+impl ForeignFrom<api_models::payments::MandateData>
+ for hyperswitch_domain_models::mandates::MandateData
+{
fn foreign_from(d: api_models::payments::MandateData) -> Self {
Self {
customer_acceptance: d.customer_acceptance.map(|d| {
- data_models::mandates::CustomerAcceptance {
+ hyperswitch_domain_models::mandates::CustomerAcceptance {
acceptance_type: match d.acceptance_type {
api_models::payments::AcceptanceType::Online => {
- data_models::mandates::AcceptanceType::Online
+ hyperswitch_domain_models::mandates::AcceptanceType::Online
}
api_models::payments::AcceptanceType::Offline => {
- data_models::mandates::AcceptanceType::Offline
+ hyperswitch_domain_models::mandates::AcceptanceType::Offline
}
},
accepted_at: d.accepted_at,
- online: d.online.map(|d| data_models::mandates::OnlineMandate {
- ip_address: d.ip_address,
- user_agent: d.user_agent,
- }),
+ online: d
+ .online
+ .map(|d| hyperswitch_domain_models::mandates::OnlineMandate {
+ ip_address: d.ip_address,
+ user_agent: d.user_agent,
+ }),
}
}),
mandate_type: d.mandate_type.map(|d| match d {
api_models::payments::MandateType::MultiUse(Some(i)) => {
- data_models::mandates::MandateDataType::MultiUse(Some(
- data_models::mandates::MandateAmountData {
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(
+ hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
@@ -348,8 +352,8 @@ impl ForeignFrom<api_models::payments::MandateData> for data_models::mandates::M
))
}
api_models::payments::MandateType::SingleUse(i) => {
- data_models::mandates::MandateDataType::SingleUse(
- data_models::mandates::MandateAmountData {
+ hyperswitch_domain_models::mandates::MandateDataType::SingleUse(
+ hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
@@ -359,7 +363,7 @@ impl ForeignFrom<api_models::payments::MandateData> for data_models::mandates::M
)
}
api_models::payments::MandateType::MultiUse(None) => {
- data_models::mandates::MandateDataType::MultiUse(None)
+ hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None)
}
}),
update_mandate_id: d.update_mandate_id,
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 2d4b34b30d5..341c560e4d2 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -23,8 +23,8 @@ pub use common_utils::{
fp_utils::when,
validation::validate_email,
};
-use data_models::payments::PaymentIntent;
use error_stack::ResultExt;
+use hyperswitch_domain_models::payments::PaymentIntent;
use image::Luma;
use masking::ExposeInterface;
use nanoid::nanoid;
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 8469bf770d2..2216cb10554 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -2,9 +2,9 @@ use api_models::{
enums::Connector::{DummyConnector4, DummyConnector7},
user::sample_data::SampleDataRequest,
};
-use data_models::payments::payment_intent::PaymentIntentNew;
use diesel_models::{user::sample_data::PaymentAttemptBatchNew, RefundNew};
use error_stack::ResultExt;
+use hyperswitch_domain_models::payments::payment_intent::PaymentIntentNew;
use rand::{prelude::SliceRandom, thread_rng, Rng};
use time::OffsetDateTime;
@@ -187,7 +187,9 @@ pub async fn generate_sample_data(
client_secret: Some(client_secret),
business_country: business_country_default,
business_label: business_label_default.clone(),
- active_attempt: data_models::RemoteStorageObject::ForeignID(attempt_id.clone()),
+ active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
+ attempt_id.clone(),
+ ),
attempt_count: 1,
customer_id: Some("hs-dashboard-user".to_string()),
amount_captured: Some(amount * 100),
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index 932a06bae6f..5dbfff8342e 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -123,9 +123,9 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow {
.as_ref()
.is_none()
{
- let payment_intent_update = data_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false) };
+ let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false) };
let payment_attempt_update =
- data_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate {
+ hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status: api_models::enums::AttemptStatus::AuthenticationFailed,
error_code: None,
diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml
index 5421e301f6a..ab656c3f658 100644
--- a/crates/storage_impl/Cargo.toml
+++ b/crates/storage_impl/Cargo.toml
@@ -11,14 +11,14 @@ license.workspace = true
[features]
default = ["olap", "oltp"]
oltp = []
-olap = ["data_models/olap"]
-payouts = ["data_models/payouts"]
+olap = ["hyperswitch_domain_models/olap"]
+payouts = ["hyperswitch_domain_models/payouts"]
[dependencies]
# First Party dependencies
api_models = { version = "0.1.0", path = "../api_models" }
common_utils = { version = "0.1.0", path = "../common_utils" }
-data_models = { version = "0.1.0", path = "../data_models", default-features = false }
+hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
diesel_models = { version = "0.1.0", path = "../diesel_models" }
masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rs
index 92ba8910bfb..17ae76b5bb0 100644
--- a/crates/storage_impl/src/database/store.rs
+++ b/crates/storage_impl/src/database/store.rs
@@ -1,8 +1,8 @@
use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::CustomizeConnection;
-use data_models::errors::{StorageError, StorageResult};
use diesel::PgConnection;
use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::{StorageError, StorageResult};
use masking::PeekInterface;
use crate::config::Database;
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 8210b29a7cf..41099bea75f 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -3,8 +3,8 @@ use std::fmt::Display;
use actix_web::ResponseError;
use common_utils::errors::ErrorSwitch;
use config::ConfigError;
-use data_models::errors::StorageError as DataStorageError;
use http::StatusCode;
+use hyperswitch_domain_models::errors::StorageError as DataStorageError;
pub use redis_interface::errors::RedisError;
use router_env::opentelemetry::metrics::MetricsError;
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index f139641a565..e35d1f41511 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -1,8 +1,8 @@
use std::sync::Arc;
-use data_models::errors::{StorageError, StorageResult};
use diesel_models as store;
use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::{StorageError, StorageResult};
use masking::StrongSecret;
use redis::{kv_store::RedisConnInterface, RedisStore};
mod address;
@@ -25,9 +25,9 @@ mod reverse_lookup;
mod utils;
use common_utils::errors::CustomResult;
-#[cfg(not(feature = "payouts"))]
-use data_models::{PayoutAttemptInterface, PayoutsInterface};
use database::store::PgPool;
+#[cfg(not(feature = "payouts"))]
+use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
pub use mock_db::MockDb;
use redis_interface::{errors::RedisError, SaddReply};
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
index fb8c8664436..f8daabf2e9e 100644
--- a/crates/storage_impl/src/lookup.rs
+++ b/crates/storage_impl/src/lookup.rs
@@ -1,5 +1,4 @@
use common_utils::errors::CustomResult;
-use data_models::errors;
use diesel_models::{
enums as storage_enums, kv,
reverse_lookup::{
@@ -7,6 +6,7 @@ use diesel_models::{
},
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::errors;
use redis_interface::SetnxReply;
use crate::{
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 77cda9817a3..5cf0123eb7b 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -1,12 +1,12 @@
use std::sync::Arc;
-use data_models::{
- errors::StorageError,
- payments::{payment_attempt::PaymentAttempt, PaymentIntent},
-};
use diesel_models::{self as store};
use error_stack::ResultExt;
use futures::lock::Mutex;
+use hyperswitch_domain_models::{
+ errors::StorageError,
+ payments::{payment_attempt::PaymentAttempt, PaymentIntent},
+};
use redis_interface::RedisSettings;
use crate::redis::RedisStore;
@@ -19,7 +19,7 @@ pub mod payout_attempt;
pub mod payouts;
pub mod redis_conn;
#[cfg(not(feature = "payouts"))]
-use data_models::{PayoutAttemptInterface, PayoutsInterface};
+use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
#[derive(Clone)]
pub struct MockDb {
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 996c8e102b7..33ef6d416f2 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -1,12 +1,12 @@
use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMethodType};
use common_utils::errors::CustomResult;
-use data_models::{
+use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::{
errors::StorageError,
payments::payment_attempt::{
PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
},
};
-use diesel_models::enums as storage_enums;
use super::MockDb;
use crate::DataModelExt;
@@ -26,11 +26,13 @@ impl PaymentAttemptInterface for MockDb {
async fn get_filters_for_payments(
&self,
- _pi: &[data_models::payments::PaymentIntent],
+ _pi: &[hyperswitch_domain_models::payments::PaymentIntent],
_merchant_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
- ) -> CustomResult<data_models::payments::payment_attempt::PaymentListFilters, StorageError>
- {
+ ) -> CustomResult<
+ hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
+ StorageError,
+ > {
Err(StorageError::MockDbError)?
}
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index a693eb5e261..1dfb7ac9d91 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -1,5 +1,7 @@
use common_utils::errors::CustomResult;
-use data_models::{
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{
errors::StorageError,
payments::{
payment_attempt::PaymentAttempt,
@@ -7,8 +9,6 @@ use data_models::{
PaymentIntent,
},
};
-use diesel_models::enums as storage_enums;
-use error_stack::ResultExt;
use super::MockDb;
use crate::DataModelExt;
@@ -19,7 +19,7 @@ impl PaymentIntentInterface for MockDb {
async fn filter_payment_intent_by_constraints(
&self,
_merchant_id: &str,
- _filters: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
@@ -39,7 +39,7 @@ impl PaymentIntentInterface for MockDb {
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &str,
- _constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
// [#172]: Implement function for `MockDb`
@@ -49,7 +49,7 @@ impl PaymentIntentInterface for MockDb {
async fn get_filtered_payment_intents_attempt(
&self,
_merchant_id: &str,
- _constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
// [#172]: Implement function for `MockDb`
@@ -159,7 +159,7 @@ impl PaymentIntentInterface for MockDb {
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, StorageError> {
match payment.active_attempt.clone() {
- data_models::RemoteStorageObject::ForeignID(id) => {
+ hyperswitch_domain_models::RemoteStorageObject::ForeignID(id) => {
let attempts = self.payment_attempts.lock().await;
let attempt = attempts
.iter()
@@ -169,7 +169,7 @@ impl PaymentIntentInterface for MockDb {
payment.active_attempt = attempt.clone().into();
Ok(attempt.clone())
}
- data_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
}
}
}
diff --git a/crates/storage_impl/src/mock_db/payout_attempt.rs b/crates/storage_impl/src/mock_db/payout_attempt.rs
index 6b792e033d1..8f26b8c5810 100644
--- a/crates/storage_impl/src/mock_db/payout_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payout_attempt.rs
@@ -1,5 +1,6 @@
use common_utils::errors::CustomResult;
-use data_models::{
+use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::{
errors::StorageError,
payouts::{
payout_attempt::{
@@ -8,7 +9,6 @@ use data_models::{
payouts::Payouts,
},
};
-use diesel_models::enums as storage_enums;
use super::MockDb;
@@ -50,7 +50,10 @@ impl PayoutAttemptInterface for MockDb {
_payouts: &[Payouts],
_merchant_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
- ) -> CustomResult<data_models::payouts::payout_attempt::PayoutListFilters, StorageError> {
+ ) -> CustomResult<
+ hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters,
+ StorageError,
+ > {
Err(StorageError::MockDbError)?
}
}
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 1aee200eed0..04e1321f1eb 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -1,12 +1,12 @@
use common_utils::errors::CustomResult;
-use data_models::{
+use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::{
errors::StorageError,
payouts::{
payout_attempt::PayoutAttempt,
payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},
},
};
-use diesel_models::enums as storage_enums;
use super::MockDb;
@@ -56,7 +56,7 @@ impl PayoutsInterface for MockDb {
async fn filter_payouts_by_constraints(
&self,
_merchant_id: &str,
- _filters: &data_models::payouts::PayoutFetchConstraints,
+ _filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
// TODO: Implement function for `MockDb`
@@ -67,7 +67,7 @@ impl PayoutsInterface for MockDb {
async fn filter_payouts_and_attempts(
&self,
_merchant_id: &str,
- _filters: &data_models::payouts::PayoutFetchConstraints,
+ _filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<(Payouts, PayoutAttempt, diesel_models::Customer)>, StorageError> {
// TODO: Implement function for `MockDb`
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 683b0469a2a..4308e463b0c 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1,16 +1,5 @@
use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMethodType};
use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found};
-use data_models::{
- errors,
- mandates::{MandateAmountData, MandateDataType, MandateDetails},
- payments::{
- payment_attempt::{
- PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
- PaymentListFilters,
- },
- PaymentIntent,
- },
-};
use diesel_models::{
enums::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
@@ -24,6 +13,17 @@ use diesel_models::{
reverse_lookup::{ReverseLookup, ReverseLookupNew},
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ errors,
+ mandates::{MandateAmountData, MandateDataType, MandateDetails},
+ payments::{
+ payment_attempt::{
+ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
+ PaymentListFilters,
+ },
+ PaymentIntent,
+ },
+};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 4d984a02cc9..fcc4ec63ff2 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -6,17 +6,6 @@ use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::errors::ReportSwitchExt;
use common_utils::{date_time, ext_traits::Encode};
#[cfg(feature = "olap")]
-use data_models::payments::payment_intent::PaymentIntentFetchConstraints;
-use data_models::{
- errors::StorageError,
- payments::{
- payment_attempt::PaymentAttempt,
- payment_intent::{PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate},
- PaymentIntent,
- },
- RemoteStorageObject,
-};
-#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};
use diesel_models::{
enums::MerchantStorageScheme,
@@ -33,6 +22,17 @@ use diesel_models::{
schema::{payment_attempt::dsl as pa_dsl, payment_intent::dsl as pi_dsl},
};
use error_stack::ResultExt;
+#[cfg(feature = "olap")]
+use hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints;
+use hyperswitch_domain_models::{
+ errors::StorageError,
+ payments::{
+ payment_attempt::PaymentAttempt,
+ payment_intent::{PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate},
+ PaymentIntent,
+ },
+ RemoteStorageObject,
+};
use redis_interface::HsetnxReply;
#[cfg(feature = "olap")]
use router_env::logger;
@@ -257,7 +257,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, StorageError> {
match payment.active_attempt.clone() {
- data_models::RemoteStorageObject::ForeignID(attempt_id) => {
+ hyperswitch_domain_models::RemoteStorageObject::ForeignID(attempt_id) => {
let conn = pg_connection_read(self).await?;
let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
@@ -271,10 +271,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)?;
- payment.active_attempt = data_models::RemoteStorageObject::Object(pa.clone());
+ payment.active_attempt =
+ hyperswitch_domain_models::RemoteStorageObject::Object(pa.clone());
Ok(pa)
}
- data_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
}
}
@@ -396,7 +397,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, StorageError> {
match &payment.active_attempt {
- data_models::RemoteStorageObject::ForeignID(attempt_id) => {
+ hyperswitch_domain_models::RemoteStorageObject::ForeignID(attempt_id) => {
let conn = pg_connection_read(self).await?;
let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
@@ -410,10 +411,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)?;
- payment.active_attempt = data_models::RemoteStorageObject::Object(pa.clone());
+ payment.active_attempt =
+ hyperswitch_domain_models::RemoteStorageObject::Object(pa.clone());
Ok(pa)
}
- data_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
}
}
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 50334442e63..6a62832e1bf 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -2,16 +2,6 @@ use std::str::FromStr;
use api_models::enums::PayoutConnectors;
use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found};
-use data_models::{
- errors,
- payouts::{
- payout_attempt::{
- PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,
- PayoutListFilters,
- },
- payouts::Payouts,
- },
-};
use diesel_models::{
enums::MerchantStorageScheme,
kv,
@@ -22,6 +12,16 @@ use diesel_models::{
ReverseLookupNew,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ errors,
+ payouts::{
+ payout_attempt::{
+ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,
+ PayoutListFilters,
+ },
+ payouts::Payouts,
+ },
+};
use redis_interface::HsetnxReply;
use router_env::{instrument, logger, tracing};
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 0b166946758..19921121a94 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -2,15 +2,6 @@
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::ext_traits::Encode;
#[cfg(feature = "olap")]
-use data_models::payouts::PayoutFetchConstraints;
-use data_models::{
- errors::StorageError,
- payouts::{
- payout_attempt::PayoutAttempt,
- payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},
- },
-};
-#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};
#[cfg(feature = "olap")]
use diesel_models::{
@@ -28,6 +19,15 @@ use diesel_models::{
},
};
use error_stack::ResultExt;
+#[cfg(feature = "olap")]
+use hyperswitch_domain_models::payouts::PayoutFetchConstraints;
+use hyperswitch_domain_models::{
+ errors::StorageError,
+ payouts::{
+ payout_attempt::PayoutAttempt,
+ payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},
+ },
+};
use redis_interface::HsetnxReply;
#[cfg(feature = "olap")]
use router_env::logger;
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index a960261f867..dc2a2225dc9 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -4,9 +4,9 @@ use common_utils::{
errors::{self, CustomResult},
ext_traits::AsyncExt,
};
-use data_models::errors::StorageError;
use dyn_clone::DynClone;
use error_stack::{Report, ResultExt};
+use hyperswitch_domain_models::errors::StorageError;
use moka::future::Cache as MokaCache;
use once_cell::sync::Lazy;
use redis_interface::{errors::RedisError, RedisValue};
diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rs
index 78198e92753..b634f41a98f 100644
--- a/crates/storage_impl/src/utils.rs
+++ b/crates/storage_impl/src/utils.rs
@@ -1,7 +1,7 @@
use bb8::PooledConnection;
-use data_models::errors::StorageError;
use diesel::PgConnection;
use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::StorageError;
use crate::{errors::RedisErrorExt, metrics, DatabaseStore};
|
2024-04-30T08:58:44Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR contains the following change:
- Create `data_models` is renamed to `hyperswitch_domain_models`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4514
https://github.com/juspay/hyperswitch/issues/4515
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Only crate renamed hence no testing required.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
22cb01ac1ecc90eee464561e4e944aad5cb3ed61
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4491
|
Bug: [BUG] : update wasm 3ds metadata config
### Bug Description
metadata config for 3ds are missing in the wasm.
### Expected Behavior
3ds metadata configs are missing so while updating the 3ds configuration in dashboard the data is not getting reflected in the dashboard
### Actual Behavior
3ds metadata configs are missing so while updating the 3ds configuration in dashboard the data is not getting reflected in the dashboard
### Steps To Reproduce
Go to control center and trying updating the netcetera 3ds
### 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/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs
index 495c0e5b6cc..b11a74a3ca6 100644
--- a/crates/connector_configs/src/common_config.rs
+++ b/crates/connector_configs/src/common_config.rs
@@ -87,6 +87,9 @@ pub struct ApiModelMetaData {
pub merchant_name: Option<String>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
+ pub three_ds_requestor_name: Option<String>,
+ pub three_ds_requestor_id: Option<String>,
+ pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
}
#[serde_with::skip_serializing_none]
@@ -185,4 +188,7 @@ pub struct DashboardMetaData {
pub merchant_name: Option<String>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
+ pub three_ds_requestor_name: Option<String>,
+ pub three_ds_requestor_id: Option<String>,
+ pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
}
diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs
index 6fbf85f4fcf..8f7da58c4dc 100644
--- a/crates/connector_configs/src/response_modifier.rs
+++ b/crates/connector_configs/src/response_modifier.rs
@@ -317,6 +317,10 @@ impl From<ApiModelMetaData> for DashboardMetaData {
merchant_name: api_model.merchant_name,
acquirer_bin: api_model.acquirer_bin,
acquirer_merchant_id: api_model.acquirer_merchant_id,
+ three_ds_requestor_name: api_model.three_ds_requestor_name,
+ three_ds_requestor_id: api_model.three_ds_requestor_id,
+ pull_mechanism_for_external_3ds_enabled: api_model
+ .pull_mechanism_for_external_3ds_enabled,
}
}
}
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 09a28ac2b07..203e48ac507 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -114,8 +114,8 @@ impl DashboardRequestPayload {
maximum_amount: Some(68607706),
recurring_enabled: true,
installment_payment_enabled: false,
- accepted_currencies: None,
- accepted_countries: None,
+ accepted_currencies: method.accepted_currencies,
+ accepted_countries: method.accepted_countries,
payment_experience: None,
};
card_payment_method_types.push(data)
@@ -192,6 +192,9 @@ impl DashboardRequestPayload {
merchant_name: None,
acquirer_bin: None,
acquirer_merchant_id: None,
+ three_ds_requestor_name: None,
+ three_ds_requestor_id: None,
+ pull_mechanism_for_external_3ds_enabled: None,
};
let meta_data = match request.metadata {
Some(data) => data,
@@ -211,6 +214,10 @@ impl DashboardRequestPayload {
let merchant_name = meta_data.merchant_name;
let acquirer_bin = meta_data.acquirer_bin;
let acquirer_merchant_id = meta_data.acquirer_merchant_id;
+ let three_ds_requestor_name = meta_data.three_ds_requestor_name;
+ let three_ds_requestor_id = meta_data.three_ds_requestor_id;
+ let pull_mechanism_for_external_3ds_enabled =
+ meta_data.pull_mechanism_for_external_3ds_enabled;
Some(ApiModelMetaData {
google_pay,
@@ -227,6 +234,9 @@ impl DashboardRequestPayload {
merchant_name,
acquirer_bin,
acquirer_merchant_id,
+ three_ds_requestor_name,
+ three_ds_requestor_id,
+ pull_mechanism_for_external_3ds_enabled,
})
}
|
2024-04-25T08:14:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The dashboard encountered an issue creating a request for 3DS because the metadata configuration for 3DS in the WebAssembly (Wasm) code is missing.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
ac9d856add0220701f809c8eb0668afe77003ef7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4496
|
Bug: [REFACTOR] Update KafkaStore to hold variables for tenant ID
Update the [`KafkaStore`](https://github.com/juspay/hyperswitch/blob/c20ecb855aa3c4b3ce1798dcc19910fb38345b46/crates/router/src/db/kafka_store.rs#L75-L79) to hold a variable for tenant-ID.
This can be achieved by simply adding a new field in the `KafkaStore` struct.
Update the KafkaStore constructor method to accept a Tenant-ID.
Tenant-ID can be a new type field backed by a string;
```rust
pub struct TenantID(String);
```
For now the KafkaStore can be initialized with a fixed tenantID `"default"`
|
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 9f9e61a5ffc..3ac9b3cc371 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -19,7 +19,7 @@ pub mod file;
pub mod fraud_check;
pub mod gsm;
pub mod health_check;
-mod kafka_store;
+pub mod kafka_store;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 7da40e505e8..f4e079489c3 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -23,6 +23,7 @@ use scheduler::{
db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface},
SchedulerInterface,
};
+use serde::Serialize;
use storage_impl::redis::kv_store::RedisConnInterface;
use time::PrimitiveDateTime;
@@ -72,17 +73,22 @@ use crate::{
},
};
+#[derive(Clone, Serialize)]
+pub struct TenantID(pub String);
+
#[derive(Clone)]
pub struct KafkaStore {
kafka_producer: KafkaProducer,
pub diesel_store: Store,
+ pub tenant_id: TenantID,
}
impl KafkaStore {
- pub async fn new(store: Store, kafka_producer: KafkaProducer) -> Self {
+ pub async fn new(store: Store, kafka_producer: KafkaProducer, tenant_id: TenantID) -> Self {
Self {
kafka_producer,
diesel_store: store,
+ tenant_id,
}
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2771ee42947..c04d30836f8 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -186,6 +186,7 @@ impl AppState {
.await
.expect("Failed to create store"),
kafka_client.clone(),
+ crate::db::kafka_store::TenantID("default".to_string()),
)
.await,
),
|
2024-05-02T04:45:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
Add TenantId field to the KafkaStore struct
#4496
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [X] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Add TenantId field to the KafkaStore struct
- Add the tenant_id parameter to the constructor of Kafkastore
### 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)?
-->
- no testable changes except CI checks
## 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
|
177fe1b8929260c5ee14f768eae4b7b29ad073ed
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4546
|
Bug: chore: address Rust 1.78 clippy lints
Address the clippy lints occurring due to new rust version 1.78
See https://github.com/juspay/hyperswitch/issues/3391 for more information.
|
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 4d01c20972c..8f0d00cd799 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -453,7 +453,7 @@ where
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
- order.to_string()
+ order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
@@ -476,7 +476,7 @@ where
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
- order.to_string()
+ order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 2a7075a0f29..ae10fc9889e 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -78,14 +78,16 @@ impl Default for AnalyticsProvider {
}
}
-impl ToString for AnalyticsProvider {
- fn to_string(&self) -> String {
- String::from(match self {
+impl std::fmt::Display for AnalyticsProvider {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let analytics_provider = match self {
Self::Clickhouse(_) => "Clickhouse",
Self::Sqlx(_) => "Sqlx",
Self::CombinedCkh(_, _) => "CombinedCkh",
Self::CombinedSqlx(_, _) => "CombinedSqlx",
- })
+ };
+
+ write!(f, "{}", analytics_provider)
}
}
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs
index c340f2888f8..efc8aaf6983 100644
--- a/crates/analytics/src/payments/accumulator.rs
+++ b/crates/analytics/src/payments/accumulator.rs
@@ -153,10 +153,7 @@ impl PaymentMetricAccumulator for SumAccumulator {
fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
self.total = match (
self.total,
- metrics
- .total
- .as_ref()
- .and_then(bigdecimal::ToPrimitive::to_i64),
+ metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
@@ -173,10 +170,7 @@ impl PaymentMetricAccumulator for AverageAccumulator {
type MetricOutput = Option<f64>;
fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
- let total = metrics
- .total
- .as_ref()
- .and_then(bigdecimal::ToPrimitive::to_u32);
+ let total = metrics.total.as_ref().and_then(ToPrimitive::to_u32);
let count = metrics.count.and_then(|total| u32::try_from(total).ok());
match (total, count) {
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index d5296152076..525bc0f8467 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -286,12 +286,12 @@ pub enum Order {
Descending,
}
-impl ToString for Order {
- fn to_string(&self) -> String {
- String::from(match self {
- Self::Ascending => "asc",
- Self::Descending => "desc",
- })
+impl std::fmt::Display for Order {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Ascending => write!(f, "asc"),
+ Self::Descending => write!(f, "desc"),
+ }
}
}
@@ -709,12 +709,12 @@ where
Ok(query)
}
- pub async fn execute_query<R, P: AnalyticsDataSource>(
+ pub async fn execute_query<R, P>(
&mut self,
store: &P,
) -> CustomResult<CustomResult<Vec<R>, QueryExecutionError>, QueryBuildingError>
where
- P: LoadRow<R>,
+ P: LoadRow<R> + AnalyticsDataSource,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
diff --git a/crates/analytics/src/refunds.rs b/crates/analytics/src/refunds.rs
index 53481e23281..590dc148ebf 100644
--- a/crates/analytics/src/refunds.rs
+++ b/crates/analytics/src/refunds.rs
@@ -6,5 +6,4 @@ pub mod metrics;
pub mod types;
pub use accumulator::{RefundMetricAccumulator, RefundMetricsAccumulator};
-pub trait RefundAnalytics: metrics::RefundMetricAnalytics {}
pub use self::core::{get_filters, get_metrics};
diff --git a/crates/analytics/src/sdk_events.rs b/crates/analytics/src/sdk_events.rs
index fe8af7cfe2d..a02de4cbbee 100644
--- a/crates/analytics/src/sdk_events.rs
+++ b/crates/analytics/src/sdk_events.rs
@@ -5,10 +5,5 @@ pub mod filters;
pub mod metrics;
pub mod types;
pub use accumulator::{SdkEventMetricAccumulator, SdkEventMetricsAccumulator};
-pub trait SDKEventAnalytics: events::SdkEventsFilterAnalytics {}
-pub trait SdkEventAnalytics:
- metrics::SdkEventMetricAnalytics + filters::SdkEventFilterAnalytics
-{
-}
pub use self::core::{get_filters, get_metrics, sdk_events_core};
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 86782c5f750..133e959d63b 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -593,7 +593,7 @@ where
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
- order.to_string()
+ order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
@@ -616,7 +616,7 @@ where
|(order_column, order)| format!(
" order by {} {}",
order_column.to_owned(),
- order.to_string()
+ order
)
),
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs
index 356d11bb77d..d0c1d74bc10 100644
--- a/crates/analytics/src/types.rs
+++ b/crates/analytics/src/types.rs
@@ -63,11 +63,6 @@ where
}
}
-// Analytics Framework
-
-pub trait RefundAnalytics {}
-pub trait SdkEventAnalytics {}
-
#[async_trait::async_trait]
pub trait AnalyticsDataSource
where
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 75bd2a31d8e..e845317b693 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -456,7 +456,7 @@ pub struct MerchantConnectorCreate {
pub disabled: Option<bool>,
/// Contains the frm configs for the merchant connector
- #[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))]
+ #[schema(example = json!(consts::FRM_CONFIGS_EG))]
pub frm_configs: Option<Vec<FrmConfigs>>,
/// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead
@@ -609,7 +609,7 @@ pub struct MerchantConnectorResponse {
pub disabled: Option<bool>,
/// Contains the frm configs for the merchant connector
- #[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))]
+ #[schema(example = json!(consts::FRM_CONFIGS_EG))]
pub frm_configs: Option<Vec<FrmConfigs>>,
/// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead
@@ -702,7 +702,7 @@ pub struct MerchantConnectorUpdate {
pub disabled: Option<bool>,
/// Contains the frm configs for the merchant connector
- #[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))]
+ #[schema(example = json!(consts::FRM_CONFIGS_EG))]
pub frm_configs: Option<Vec<FrmConfigs>>,
pub pm_auth_config: Option<serde_json::Value>,
diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs
index 805c5616c2a..801bbc63f5f 100644
--- a/crates/api_models/src/api_keys.rs
+++ b/crates/api_models/src/api_keys.rs
@@ -270,7 +270,7 @@ mod api_key_expiration_tests {
let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap();
let time = time::Time::from_hms(11, 12, 13).unwrap();
assert_eq!(
- serde_json::to_string(&ApiKeyExpiration::DateTime(time::PrimitiveDateTime::new(
+ serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new(
date, time
)))
.unwrap(),
@@ -289,7 +289,7 @@ mod api_key_expiration_tests {
let time = time::Time::from_hms(11, 12, 13).unwrap();
assert_eq!(
serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(),
- ApiKeyExpiration::DateTime(time::PrimitiveDateTime::new(date, time))
+ ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time))
);
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 8270ddaf3fe..0e46eb19931 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -682,7 +682,7 @@ impl PaymentsRequest {
.as_ref()
.map(|od| {
od.iter()
- .map(|order| order.encode_to_value().map(masking::Secret::new))
+ .map(|order| order.encode_to_value().map(Secret::new))
.collect::<Result<Vec<_>, _>>()
})
.transpose()
@@ -1304,9 +1304,7 @@ mod payment_method_data_serde {
match deserialize_to_inner {
__Inner::OptionalPaymentMethod(value) => {
let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value)
- .map_err(|serde_json_error| {
- serde::de::Error::custom(serde_json_error.to_string())
- })?;
+ .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?;
let payment_method_data = if let Some(payment_method_data_value) =
parsed_value.payment_method_data
@@ -1321,14 +1319,12 @@ mod payment_method_data_serde {
payment_method_data_value,
)
.map_err(|serde_json_error| {
- serde::de::Error::custom(serde_json_error.to_string())
+ de::Error::custom(serde_json_error.to_string())
})?,
)
}
} else {
- Err(serde::de::Error::custom(
- "Expected a map for payment_method_data",
- ))?
+ Err(de::Error::custom("Expected a map for payment_method_data"))?
}
} else {
None
@@ -1342,7 +1338,7 @@ mod payment_method_data_serde {
__Inner::RewardString(inner_string) => {
let payment_method_data = match inner_string.as_str() {
"reward" => PaymentMethodData::Reward,
- _ => Err(serde::de::Error::custom("Invalid Variant"))?,
+ _ => Err(de::Error::custom("Invalid Variant"))?,
};
Ok(Some(PaymentMethodDataRequest {
@@ -2686,8 +2682,8 @@ pub enum PaymentIdType {
PreprocessingId(String),
}
-impl std::fmt::Display for PaymentIdType {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl fmt::Display for PaymentIdType {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PaymentIntentId(payment_id) => {
write!(f, "payment_intent_id = \"{payment_id}\"")
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 723e6eccc36..fb9f5af8d2a 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -203,8 +203,8 @@ pub struct RoutableConnectorChoice {
pub sub_label: Option<String>,
}
-impl ToString for RoutableConnectorChoice {
- fn to_string(&self) -> String {
+impl std::fmt::Display for RoutableConnectorChoice {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
#[cfg(feature = "connector_choice_mca_id")]
let base = self.connector.to_string();
@@ -219,7 +219,7 @@ impl ToString for RoutableConnectorChoice {
sub_base
};
- base
+ write!(f, "{}", base)
}
}
@@ -336,7 +336,7 @@ pub enum RoutingAlgorithm {
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
#[schema(value_type=ProgramConnectorSelection)]
- Advanced(euclid::frontend::ast::Program<ConnectorSelection>),
+ Advanced(ast::Program<ConnectorSelection>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -345,7 +345,7 @@ pub enum RoutingAlgorithmSerde {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
- Advanced(euclid::frontend::ast::Program<ConnectorSelection>),
+ Advanced(ast::Program<ConnectorSelection>),
}
impl TryFrom<RoutingAlgorithmSerde> for RoutingAlgorithm {
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs
index b547a61d450..d8a437e31a6 100644
--- a/crates/api_models/src/user/dashboard_metadata.rs
+++ b/crates/api_models/src/user/dashboard_metadata.rs
@@ -33,7 +33,7 @@ pub enum SetMetaDataRequest {
pub struct ProductionAgreementRequest {
pub version: String,
#[serde(skip_deserializing)]
- pub ip_address: Option<Secret<String, common_utils::pii::IpAddress>>,
+ pub ip_address: Option<Secret<String, pii::IpAddress>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs
index 46904535f01..7901dec6db2 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -38,14 +38,14 @@ impl NonceSequence {
}
/// Returns the current nonce value as bytes.
- fn current(&self) -> [u8; ring::aead::NONCE_LEN] {
- let mut nonce = [0_u8; ring::aead::NONCE_LEN];
+ fn current(&self) -> [u8; aead::NONCE_LEN] {
+ let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
nonce
}
/// Constructs a nonce sequence from bytes
- fn from_bytes(bytes: [u8; ring::aead::NONCE_LEN]) -> Self {
+ fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self {
let mut sequence_number = [0_u8; 128 / 8];
sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes);
let sequence_number = u128::from_be_bytes(sequence_number);
@@ -53,16 +53,16 @@ impl NonceSequence {
}
}
-impl ring::aead::NonceSequence for NonceSequence {
- fn advance(&mut self) -> Result<ring::aead::Nonce, ring::error::Unspecified> {
- let mut nonce = [0_u8; ring::aead::NONCE_LEN];
+impl aead::NonceSequence for NonceSequence {
+ fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
+ let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
// Increment sequence number
self.0 = self.0.wrapping_add(1);
// Return previous sequence number as bytes
- Ok(ring::aead::Nonce::assume_unique_for_key(nonce))
+ Ok(aead::Nonce::assume_unique_for_key(nonce))
}
}
@@ -275,8 +275,8 @@ impl DecodeMessage for GcmAes256 {
.change_context(errors::CryptoError::DecodingFailed)?;
let nonce_sequence = NonceSequence::from_bytes(
- <[u8; ring::aead::NONCE_LEN]>::try_from(
- msg.get(..ring::aead::NONCE_LEN)
+ <[u8; aead::NONCE_LEN]>::try_from(
+ msg.get(..aead::NONCE_LEN)
.ok_or(errors::CryptoError::DecodingFailed)
.attach_printable("Failed to read the nonce form the encrypted ciphertext")?,
)
@@ -288,7 +288,7 @@ impl DecodeMessage for GcmAes256 {
let output = binding.as_mut_slice();
let result = key
- .open_within(aead::Aad::empty(), output, ring::aead::NONCE_LEN..)
+ .open_within(aead::Aad::empty(), output, aead::NONCE_LEN..)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(result.to_vec())
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs
index f71e098a99c..5ad53ec8533 100644
--- a/crates/common_utils/src/ext_traits.rs
+++ b/crates/common_utils/src/ext_traits.rs
@@ -472,13 +472,13 @@ pub trait XmlExt {
///
/// Deserialize an XML string into the specified type `<T>`.
///
- fn parse_xml<T>(self) -> Result<T, quick_xml::de::DeError>
+ fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned;
}
impl XmlExt for &str {
- fn parse_xml<T>(self) -> Result<T, quick_xml::de::DeError>
+ fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned,
{
diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs
index c1f9d716e4b..9c70c572fed 100644
--- a/crates/common_utils/src/pii.rs
+++ b/crates/common_utils/src/pii.rs
@@ -38,7 +38,7 @@ pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>);
impl<T> Strategy<T> for PhoneNumberStrategy
where
- T: AsRef<str> + std::fmt::Debug,
+ T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
@@ -85,7 +85,7 @@ impl ops::DerefMut for PhoneNumber {
}
}
-impl<DB> Queryable<diesel::sql_types::Text, DB> for PhoneNumber
+impl<DB> Queryable<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
@@ -210,7 +210,7 @@ pub enum EmailStrategy {}
impl<T> Strategy<T> for EmailStrategy
where
- T: AsRef<str> + std::fmt::Debug,
+ T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
@@ -224,7 +224,7 @@ where
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression,
)]
-#[diesel(sql_type = diesel::sql_types::Text)]
+#[diesel(sql_type = sql_types::Text)]
#[serde(try_from = "String")]
pub struct Email(Secret<String, EmailStrategy>);
@@ -262,7 +262,7 @@ impl ops::DerefMut for Email {
}
}
-impl<DB> Queryable<diesel::sql_types::Text, DB> for Email
+impl<DB> Queryable<sql_types::Text, DB> for Email
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
@@ -353,7 +353,7 @@ pub enum UpiVpaMaskingStrategy {}
impl<T> Strategy<T> for UpiVpaMaskingStrategy
where
- T: AsRef<str> + std::fmt::Debug,
+ T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let vpa_str: &str = val.as_ref();
diff --git a/crates/common_utils/src/static_cache.rs b/crates/common_utils/src/static_cache.rs
index ca608fa9a3b..37705c892c5 100644
--- a/crates/common_utils/src/static_cache.rs
+++ b/crates/common_utils/src/static_cache.rs
@@ -26,6 +26,8 @@ impl<T> StaticCache<T>
where
T: Send,
{
+ // Cannot have default impl as it cannot be called during instantiation of static item
+ #[allow(clippy::new_without_default)]
pub const fn new() -> Self {
Self {
data: Lazy::new(|| RwLock::new(FxHashMap::default())),
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 203e48ac507..f89c2e5921b 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -98,12 +98,11 @@ impl DashboardRequestPayload {
if let Some(payment_methods_enabled) = request.payment_methods_enabled.clone() {
for payload in payment_methods_enabled {
match payload.payment_method {
- api_models::enums::PaymentMethod::Card => {
+ PaymentMethod::Card => {
if let Some(card_provider) = payload.card_provider {
- let payment_type = api_models::enums::PaymentMethodType::from_str(
- &payload.payment_method_type,
- )
- .map_err(|_| "Invalid key received".to_string());
+ let payment_type =
+ PaymentMethodType::from_str(&payload.payment_method_type)
+ .map_err(|_| "Invalid key received".to_string());
if let Ok(payment_type) = payment_type {
for method in card_provider {
@@ -124,17 +123,17 @@ impl DashboardRequestPayload {
}
}
- api_models::enums::PaymentMethod::Wallet
- | api_models::enums::PaymentMethod::BankRedirect
- | api_models::enums::PaymentMethod::PayLater
- | api_models::enums::PaymentMethod::BankTransfer
- | api_models::enums::PaymentMethod::Crypto
- | api_models::enums::PaymentMethod::BankDebit
- | api_models::enums::PaymentMethod::Reward
- | api_models::enums::PaymentMethod::Upi
- | api_models::enums::PaymentMethod::Voucher
- | api_models::enums::PaymentMethod::GiftCard
- | api_models::enums::PaymentMethod::CardRedirect => {
+ PaymentMethod::Wallet
+ | PaymentMethod::BankRedirect
+ | PaymentMethod::PayLater
+ | PaymentMethod::BankTransfer
+ | PaymentMethod::Crypto
+ | PaymentMethod::BankDebit
+ | PaymentMethod::Reward
+ | PaymentMethod::Upi
+ | PaymentMethod::Voucher
+ | PaymentMethod::GiftCard
+ | PaymentMethod::CardRedirect => {
if let Some(provider) = payload.provider {
let val = Self::transform_payment_method(
request.connector,
@@ -154,7 +153,7 @@ impl DashboardRequestPayload {
}
if !card_payment_method_types.is_empty() {
let card = PaymentMethodsEnabled {
- payment_method: api_models::enums::PaymentMethod::Card,
+ payment_method: PaymentMethod::Card,
payment_method_types: Some(card_payment_method_types),
};
payment_method_enabled.push(card);
diff --git a/crates/diesel_models/src/encryption.rs b/crates/diesel_models/src/encryption.rs
index 375259491c9..6c6063c1604 100644
--- a/crates/diesel_models/src/encryption.rs
+++ b/crates/diesel_models/src/encryption.rs
@@ -8,7 +8,7 @@ use diesel::{
use masking::Secret;
#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
-#[diesel(sql_type = diesel::sql_types::Binary)]
+#[diesel(sql_type = sql_types::Binary)]
#[repr(transparent)]
pub struct Encryption {
inner: Secret<Vec<u8>, EncryptionStrategy>,
@@ -41,7 +41,7 @@ where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>,
{
- fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
<Secret<Vec<u8>, EncryptionStrategy>>::from_sql(bytes).map(Self::new)
}
}
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index f23c2318899..4e5773800aa 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -10,7 +10,7 @@ use error_stack::{report, ResultExt};
use super::generics;
use crate::{
enums::{self, IntentStatus},
- errors::{self, DatabaseError},
+ errors::DatabaseError,
payment_attempt::{
PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal,
},
@@ -246,7 +246,7 @@ impl PaymentAttempt {
.distinct()
.get_results_async::<Option<String>>(conn)
.await
- .change_context(errors::DatabaseError::Others)
+ .change_context(DatabaseError::Others)
.attach_printable("Error filtering records by connector")?
.into_iter()
.flatten()
@@ -350,7 +350,7 @@ impl PaymentAttempt {
db_metrics::DatabaseOperation::Filter,
)
.await
- .change_context(errors::DatabaseError::Others)
+ .change_context(DatabaseError::Others)
.attach_printable("Error filtering count of payments")
}
}
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index ac34ee695ac..4f95877bd7c 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -11,7 +11,7 @@ use error_stack::{report, ResultExt};
use super::generics;
use crate::{
enums,
- errors::{self, DatabaseError},
+ errors::DatabaseError,
payout_attempt::{
PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,
},
@@ -46,7 +46,7 @@ impl PayoutAttempt {
.await
{
Err(error) => match error.current_context() {
- errors::DatabaseError::NoFieldsToUpdate => Ok(self),
+ DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
@@ -98,7 +98,7 @@ impl PayoutAttempt {
.first()
.cloned()
.ok_or_else(|| {
- report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout")
+ report!(DatabaseError::NotFound).attach_printable("Error while updating payout")
})
}
@@ -119,7 +119,7 @@ impl PayoutAttempt {
.first()
.cloned()
.ok_or_else(|| {
- report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout")
+ report!(DatabaseError::NotFound).attach_printable("Error while updating payout")
})
}
@@ -161,7 +161,7 @@ impl PayoutAttempt {
.distinct()
.get_results_async::<Option<String>>(conn)
.await
- .change_context(errors::DatabaseError::Others)
+ .change_context(DatabaseError::Others)
.attach_printable("Error filtering records by connector")?
.into_iter()
.flatten()
diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs
index 47b60db80d5..35ad467d5fe 100644
--- a/crates/drainer/src/handler.rs
+++ b/crates/drainer/src/handler.rs
@@ -95,7 +95,7 @@ impl Handler {
while let Some(_c) = rx.recv().await {
logger::info!("Awaiting shutdown!");
metrics::SHUTDOWN_SIGNAL_RECEIVED.add(&metrics::CONTEXT, 1, &[]);
- let shutdown_started = tokio::time::Instant::now();
+ let shutdown_started = time::Instant::now();
rx.close();
//Check until the active tasks are zero. This does not include the tasks in the stream.
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index 56f2db0907e..cb2b55d202f 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -24,7 +24,7 @@ use router_env::{
};
use tokio::sync::mpsc;
-pub(crate) type Settings = crate::settings::Settings<RawSecret>;
+pub(crate) type Settings = settings::Settings<RawSecret>;
use crate::{
connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData,
diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs
index 526248a3817..0ffafe4d48b 100644
--- a/crates/euclid/src/dssa/graph.rs
+++ b/crates/euclid/src/dssa/graph.rs
@@ -838,7 +838,7 @@ mod test {
None::<()>,
);
let mut memo = cgraph::Memoization::new();
- let mut cycle_map = cgraph::CycleCheck::new();
+ let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
@@ -894,7 +894,7 @@ mod test {
None::<()>,
);
let mut memo = cgraph::Memoization::new();
- let mut cycle_map = cgraph::CycleCheck::new();
+ let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
@@ -986,7 +986,7 @@ mod test {
);
let mut memo = cgraph::Memoization::new();
- let mut cycle_map = cgraph::CycleCheck::new();
+ let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
diff --git a/crates/euclid/src/frontend/ast/parser.rs b/crates/euclid/src/frontend/ast/parser.rs
index 8b2f717a868..cbfc21c96a7 100644
--- a/crates/euclid/src/frontend/ast/parser.rs
+++ b/crates/euclid/src/frontend/ast/parser.rs
@@ -3,7 +3,7 @@ use nom::{
};
use crate::{frontend::ast, types::DummyOutput};
-pub type ParseResult<T, U> = nom::IResult<T, U, nom::error::VerboseError<T>>;
+pub type ParseResult<T, U> = nom::IResult<T, U, error::VerboseError<T>>;
pub enum EuclidError {
InvalidPercentage(String),
@@ -50,9 +50,9 @@ impl EuclidParsable for DummyOutput {
)(input)
}
}
-pub fn skip_ws<'a, F: 'a, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&str, O>
+pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&str, O>
where
- F: FnMut(&'a str) -> ParseResult<&str, O>,
+ F: FnMut(&'a str) -> ParseResult<&str, O> + 'a,
{
sequence::preceded(pchar::multispace0, inner)
}
diff --git a/crates/euclid_macros/src/inner/knowledge.rs b/crates/euclid_macros/src/inner/knowledge.rs
index a9c453b42c6..baef55338f0 100644
--- a/crates/euclid_macros/src/inner/knowledge.rs
+++ b/crates/euclid_macros/src/inner/knowledge.rs
@@ -1,4 +1,8 @@
-use std::{hash::Hash, rc::Rc};
+use std::{
+ fmt::{Display, Formatter},
+ hash::Hash,
+ rc::Rc,
+};
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
@@ -24,15 +28,16 @@ enum Comparison {
LessThanEqual,
}
-impl ToString for Comparison {
- fn to_string(&self) -> String {
- match self {
- Self::LessThan => "< ".to_string(),
- Self::Equal => String::new(),
- Self::GreaterThanEqual => ">= ".to_string(),
- Self::LessThanEqual => "<= ".to_string(),
- Self::GreaterThan => "> ".to_string(),
- }
+impl Display for Comparison {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ let symbol = match self {
+ Self::LessThan => "< ",
+ Self::Equal => return Ok(()),
+ Self::GreaterThanEqual => ">= ",
+ Self::LessThanEqual => "<= ",
+ Self::GreaterThan => "> ",
+ };
+ write!(f, "{}", symbol)
}
}
@@ -69,7 +74,7 @@ impl ValueType {
Self::Any => format!("{key}(any)"),
Self::EnumVariant(s) => format!("{key}({s})"),
Self::Number { number, comparison } => {
- format!("{}({}{})", key, comparison.to_string(), number)
+ format!("{}({}{})", key, comparison, number)
}
}
}
@@ -104,9 +109,9 @@ struct Atom {
value: ValueType,
}
-impl ToString for Atom {
- fn to_string(&self) -> String {
- self.value.to_string(&self.key)
+impl Display for Atom {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.value.to_string(&self.key))
}
}
@@ -317,15 +322,14 @@ impl Parse for Scope {
}
}
-impl ToString for Scope {
- fn to_string(&self) -> String {
+impl Display for Scope {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
- Self::Crate => "crate".to_string(),
- Self::Extern => "euclid".to_string(),
+ Self::Crate => write!(f, "crate"),
+ Self::Extern => write!(f, "euclid"),
}
}
}
-
#[derive(Clone)]
struct Program {
rules: Vec<Rc<Rule>>,
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs
index 4920243bcc0..3668130608e 100644
--- a/crates/euclid_wasm/src/lib.rs
+++ b/crates/euclid_wasm/src/lib.rs
@@ -193,9 +193,7 @@ pub fn run_program(program: JsValue, input: JsValue) -> JsResult {
#[wasm_bindgen(js_name = getAllConnectors)]
pub fn get_all_connectors() -> JsResult {
- Ok(serde_wasm_bindgen::to_value(
- common_enums::RoutableConnectors::VARIANTS,
- )?)
+ Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?)
}
#[wasm_bindgen(js_name = getAllKeys)]
diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs
index 912ddc67058..180f733cfeb 100644
--- a/crates/hyperswitch_domain_models/src/mandates.rs
+++ b/crates/hyperswitch_domain_models/src/mandates.rs
@@ -169,8 +169,7 @@ impl CustomerAcceptance {
}
pub fn get_accepted_at(&self) -> PrimitiveDateTime {
- self.accepted_at
- .unwrap_or_else(common_utils::date_time::now)
+ self.accepted_at.unwrap_or_else(date_time::now)
}
}
diff --git a/crates/masking/src/diesel.rs b/crates/masking/src/diesel.rs
index f3576298bdb..ea60a861c9d 100644
--- a/crates/masking/src/diesel.rs
+++ b/crates/masking/src/diesel.rs
@@ -52,7 +52,7 @@ where
S: FromSql<T, DB>,
I: Strategy<S>,
{
- fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
S::from_sql(bytes).map(|raw| raw.into())
}
}
@@ -122,7 +122,7 @@ where
S: FromSql<T, DB> + ZeroizableSecret,
I: Strategy<S>,
{
- fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
S::from_sql(bytes).map(|raw| raw.into())
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 1e384408397..7abbc3b77e4 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -514,6 +514,8 @@ Never share your secret api keys. Keep them guarded and secure.
)),
modifiers(&SecurityAddon)
)]
+// Bypass clippy lint for not being constructed
+#[allow(dead_code)]
pub struct ApiDoc;
struct SecurityAddon;
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index 51fd796072b..d5c66b9c64a 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -110,12 +110,12 @@ pub type BankDetailsRouterData = PaymentAuthRouterData<
>;
pub type PaymentAuthLinkTokenType =
- dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
+ dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
pub type PaymentAuthExchangeTokenType =
- dyn self::api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
+ dyn api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
-pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration<
+pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index d509cf03d3c..8eb94a29124 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -114,7 +114,7 @@ pub mod routes {
pub async fn get_info(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
- domain: actix_web::web::Path<analytics::AnalyticsDomain>,
+ domain: web::Path<analytics::AnalyticsDomain>,
) -> impl Responder {
let flow = AnalyticsFlow::GetInfo;
Box::pin(api::server_wrap(
@@ -631,7 +631,7 @@ pub mod routes {
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetSearchRequest>,
- index: actix_web::web::Path<SearchIndex>,
+ index: web::Path<SearchIndex>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSearchResults;
let indexed_req = GetSearchRequestWithIndex {
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 47f41d8700f..5341a1b09c1 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -40,7 +40,7 @@ async fn main() -> CustomResult<(), ProcessTrackerError> {
conf.proxy.clone(),
services::proxy_bypass_urls(&conf.locker),
)
- .change_context(errors::ProcessTrackerError::ConfigurationError)?,
+ .change_context(ProcessTrackerError::ConfigurationError)?,
);
// channel for listening to redis disconnect events
let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel();
@@ -320,7 +320,7 @@ async fn start_scheduler(
.conf
.scheduler
.clone()
- .ok_or(errors::ProcessTrackerError::ConfigurationError)?;
+ .ok_or(ProcessTrackerError::ConfigurationError)?;
scheduler::start_process_tracker(
state,
scheduler_flow,
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index eed80a1128e..3d5264ddbed 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -649,7 +649,7 @@ fn from_timestamp_to_datetime(
}
})?;
- Ok(Some(time::PrimitiveDateTime::new(time.date(), time.time())))
+ Ok(Some(PrimitiveDateTime::new(time.date(), time.time())))
} else {
Ok(None)
}
@@ -744,7 +744,7 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::
},
))),
},
- None => Some(api_models::payments::MandateType::MultiUse(Some(
+ None => Some(payments::MandateType::MultiUse(Some(
payments::MandateAmountData {
amount: mandate.amount.unwrap_or_default(),
currency,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index adc09fb55af..5b55ca8b0e3 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -200,7 +200,7 @@ pub struct ApplepayMerchantConfigs {
#[derive(Debug, Deserialize, Clone, Default)]
pub struct MultipleApiVersionSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
- pub supported_connectors: HashSet<api_models::enums::Connector>,
+ pub supported_connectors: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -214,10 +214,10 @@ pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMet
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorCustomer {
#[serde(deserialize_with = "deserialize_hashset")]
- pub connector_list: HashSet<api_models::enums::Connector>,
+ pub connector_list: HashSet<enums::Connector>,
#[cfg(feature = "payouts")]
#[serde(deserialize_with = "deserialize_hashset")]
- pub payout_connector_list: HashSet<api_models::enums::PayoutConnectors>,
+ pub payout_connector_list: HashSet<enums::PayoutConnectors>,
}
#[cfg(feature = "dummy_connector")]
@@ -263,7 +263,7 @@ pub struct Mandates {
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NetworkTransactionIdSupportedConnectors {
#[serde(deserialize_with = "deserialize_hashset")]
- pub connector_list: HashSet<api_models::enums::Connector>,
+ pub connector_list: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone)]
@@ -279,7 +279,7 @@ pub struct SupportedPaymentMethodTypesForMandate(
#[derive(Debug, Deserialize, Clone)]
pub struct SupportedConnectorsForMandate {
#[serde(deserialize_with = "deserialize_hashset")]
- pub connector_list: HashSet<api_models::enums::Connector>,
+ pub connector_list: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -322,9 +322,7 @@ pub enum PaymentMethodTypeTokenFilter {
}
#[derive(Debug, Deserialize, Clone, Default)]
-pub struct BankRedirectConfig(
- pub HashMap<api_models::enums::PaymentMethodType, ConnectorBankNames>,
-);
+pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>);
#[derive(Debug, Deserialize, Clone)]
pub struct ConnectorBankNames(pub HashMap<String, BanksVector>);
@@ -345,17 +343,17 @@ pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCoun
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum PaymentMethodFilterKey {
- PaymentMethodType(api_models::enums::PaymentMethodType),
- CardNetwork(api_models::enums::CardNetwork),
+ PaymentMethodType(enums::PaymentMethodType),
+ CardNetwork(enums::CardNetwork),
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct CurrencyCountryFlowFilter {
#[serde(deserialize_with = "deserialize_optional_hashset")]
- pub currency: Option<HashSet<api_models::enums::Currency>>,
+ pub currency: Option<HashSet<enums::Currency>>,
#[serde(deserialize_with = "deserialize_optional_hashset")]
- pub country: Option<HashSet<api_models::enums::CountryAlpha2>>,
+ pub country: Option<HashSet<enums::CountryAlpha2>>,
pub not_available_flows: Option<NotAvailableFlows>,
}
@@ -628,13 +626,13 @@ pub struct ApiKeys {
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DelayedSessionConfig {
#[serde(deserialize_with = "deserialize_hashset")]
- pub connectors_with_delayed_session_response: HashSet<api_models::enums::Connector>,
+ pub connectors_with_delayed_session_response: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct WebhookSourceVerificationCall {
#[serde(deserialize_with = "deserialize_hashset")]
- pub connectors_with_webhook_source_verification_call: HashSet<api_models::enums::Connector>,
+ pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>,
}
#[derive(Debug, Deserialize, Clone, Default)]
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 23288e3819d..9353b848bdb 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -22,20 +22,13 @@ pub struct AciRouterData<T> {
router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for AciRouterData<T>
-{
+impl<T> TryFrom<(&types::api::CurrencyUnit, 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,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 6dfe899f2d1..77abaacf40b 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1720,7 +1720,7 @@ fn get_amount_data(item: &AdyenRouterData<&types::PaymentsAuthorizeRouterData>)
}
fn get_address_info(
- address: Option<&api_models::payments::Address>,
+ address: Option<&payments::Address>,
) -> Option<Result<Address, error_stack::Report<errors::ConnectorError>>> {
address.and_then(|add| {
add.address.as_ref().map(
@@ -1783,7 +1783,7 @@ fn get_telephone_number(item: &types::PaymentsAuthorizeRouterData) -> Option<Sec
})
}
-fn get_shopper_name(address: Option<&api_models::payments::Address>) -> Option<ShopperName> {
+fn get_shopper_name(address: Option<&payments::Address>) -> Option<ShopperName> {
let billing = address.and_then(|billing| billing.address.as_ref());
Some(ShopperName {
first_name: billing.and_then(|a| a.first_name.clone()),
@@ -1791,9 +1791,7 @@ fn get_shopper_name(address: Option<&api_models::payments::Address>) -> Option<S
})
}
-fn get_country_code(
- address: Option<&api_models::payments::Address>,
-) -> Option<api_enums::CountryAlpha2> {
+fn get_country_code(address: Option<&payments::Address>) -> Option<api_enums::CountryAlpha2> {
address.and_then(|billing| billing.address.as_ref().and_then(|address| address.country))
}
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index 91a27fc3df0..bdd842bf958 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -223,7 +223,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -312,7 +312,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -442,7 +442,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -523,7 +523,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -614,7 +614,7 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -703,7 +703,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -779,7 +779,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -892,7 +892,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -965,7 +965,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index e80909d7e01..fe0cd021ebc 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -59,20 +59,13 @@ pub struct AirwallexRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for AirwallexRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, 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,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 7f9cdc376e1..2ca78e630fa 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -39,8 +39,7 @@ where
&self,
_req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError>
- {
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index a072fcf3214..ca8b13298b0 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -46,22 +46,10 @@ pub struct AuthorizedotnetRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for AuthorizedotnetRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, 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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index dbb655c6ca0..77c91af709d 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -20,22 +20,10 @@ pub struct BamboraRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for BamboraRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BamboraRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = crate::connector::utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs
index 0c01facf386..e5ddd3743b9 100644
--- a/crates/router/src/connector/bankofamerica.rs
+++ b/crates/router/src/connector/bankofamerica.rs
@@ -120,8 +120,7 @@ where
&self,
req: &types::RouterData<Flow, Request, Response>,
connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError>
- {
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let date = OffsetDateTime::now_utc();
let boa_req = self.get_request_body(req, connectors)?;
let http_method = self.get_http_method();
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index efece7f61fb..2d7b2307039 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -58,22 +58,10 @@ pub struct BankOfAmericaRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for BankOfAmericaRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BankOfAmericaRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
@@ -602,7 +590,7 @@ impl
merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
reason: None,
original_authorized_amount: Some(utils::get_amount_as_string(
- &types::api::CurrencyUnit::Base,
+ &api::CurrencyUnit::Base,
original_amount,
original_currency,
)?),
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs
index 4e91a2c9ffb..3e5e53286e3 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/router/src/connector/billwerk/transformers.rs
@@ -14,22 +14,10 @@ pub struct BillwerkRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for BillwerkRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BillwerkRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index 74fa0b5c595..a70c4ba3ac2 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -15,20 +15,13 @@ pub struct BitpayRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for BitpayRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, 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,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
@@ -81,7 +74,7 @@ impl TryFrom<&ConnectorAuthType> for BitpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 2a572a2231a..0630fef2748 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -36,22 +36,10 @@ pub struct BluesnapRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for BluesnapRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BluesnapRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
@@ -150,7 +138,7 @@ pub struct BluesnapGooglePayObject {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapApplePayObject {
- token: api_models::payments::ApplePayWalletData,
+ token: payments::ApplePayWalletData,
}
#[derive(Debug, Serialize)]
@@ -447,23 +435,19 @@ impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken {
let apple_pay_metadata = item.get_connector_meta()?.expose();
let applepay_metadata = apple_pay_metadata
.clone()
- .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
+ .parse_value::<payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
- api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
+ payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
apple_pay_metadata
- .parse_value::<api_models::payments::ApplepaySessionTokenData>(
- "ApplepaySessionTokenData",
- )
+ .parse_value::<payments::ApplepaySessionTokenData>("ApplepaySessionTokenData")
.map(|old_metadata| {
- api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
- old_metadata.apple_pay,
- )
+ payments::ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
@@ -500,31 +484,26 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons
.decode(response.wallet_token.clone().expose())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
- let session_response: api_models::payments::NoThirdPartySdkSessionResponse =
- wallet_token[..]
- .parse_struct("NoThirdPartySdkSessionResponse")
- .change_context(errors::ConnectorError::ParsingFailed)?;
+ let session_response: payments::NoThirdPartySdkSessionResponse = wallet_token
+ .parse_struct("NoThirdPartySdkSessionResponse")
+ .change_context(errors::ConnectorError::ParsingFailed)?;
let metadata = item.data.get_connector_meta()?.expose();
let applepay_metadata = metadata
.clone()
- .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
+ .parse_value::<payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
- api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
+ payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
metadata
- .parse_value::<api_models::payments::ApplepaySessionTokenData>(
- "ApplepaySessionTokenData",
- )
+ .parse_value::<payments::ApplepaySessionTokenData>("ApplepaySessionTokenData")
.map(|old_metadata| {
- api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
- old_metadata.apple_pay,
- )
+ payments::ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
@@ -543,16 +522,15 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons
Ok(Self {
response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: types::api::SessionToken::ApplePay(Box::new(
- api_models::payments::ApplepaySessionTokenResponse {
- session_token_data:
- api_models::payments::ApplePaySessionResponse::NoThirdPartySdk(
- session_response,
- ),
- payment_request_data: Some(api_models::payments::ApplePayPaymentRequest {
+ session_token: api::SessionToken::ApplePay(Box::new(
+ payments::ApplepaySessionTokenResponse {
+ session_token_data: payments::ApplePaySessionResponse::NoThirdPartySdk(
+ session_response,
+ ),
+ payment_request_data: Some(payments::ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code: item.data.request.currency,
- total: api_models::payments::AmountInfo {
+ total: payments::AmountInfo {
label: payment_request_data.label,
total_type: Some("final".to_string()),
amount: item.data.request.amount.to_string(),
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index 07b48a5353c..c22b6567732 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -295,7 +295,7 @@ fn get_authorize_response(
let redirection_data = match response.hosted {
Some(hosted_value) => Ok(hosted_value
.redirect_url
- .map(|url| services::RedirectForm::from((url, services::Method::Get)))),
+ .map(|url| RedirectForm::from((url, services::Method::Get)))),
None => Err(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirect_url",
}),
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 1b55f12cab1..f7e142a9af9 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -1467,10 +1467,8 @@ impl api::IncomingWebhook for Braintree {
match response.dispute {
Some(dispute_data) => {
- let currency = diesel_models::enums::Currency::from_str(
- dispute_data.currency_iso_code.as_str(),
- )
- .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+ let currency = enums::Currency::from_str(dispute_data.currency_iso_code.as_str())
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api::disputes::DisputePayload {
amount: connector_utils::to_currency_lower_unit(
dispute_data.amount_disputed.to_string(),
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index 480867c6cbd..bd860e72900 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -27,22 +27,10 @@ pub struct BraintreeRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for BraintreeRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BraintreeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (currency_unit, currency, amount, item): (
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
@@ -80,7 +68,7 @@ pub enum BraintreePaymentsRequest {
#[derive(Debug, Deserialize)]
pub struct BraintreeMeta {
merchant_account_id: Secret<String>,
- merchant_config_currency: types::storage::enums::Currency,
+ merchant_config_currency: enums::Currency,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index ef111a2588a..e278ff40b43 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -21,7 +21,7 @@ pub struct PaymentOptions {
#[derive(Debug, Deserialize)]
pub struct BraintreeMeta {
merchant_account_id: Option<Secret<String>>,
- merchant_config_currency: Option<types::storage::enums::Currency>,
+ merchant_config_currency: Option<enums::Currency>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
@@ -304,7 +304,7 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: types::api::SessionToken::Paypal(Box::new(
+ session_token: api::SessionToken::Paypal(Box::new(
payments::PaypalSessionTokenResponse {
session_token: item.response.client_token.value.expose(),
},
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs
index 525b19df001..f8c275df33b 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/router/src/connector/cashtocode/transformers.rs
@@ -203,13 +203,13 @@ fn get_redirect_form_data(
enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
- method: services::Method::Post,
+ method: Method::Post,
form_fields: Default::default(),
}),
enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
- services::Method::Get,
+ Method::Get,
))),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CashToCode"),
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 3fff6d940d6..cc937c0ef60 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -23,22 +23,10 @@ pub struct CheckoutRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for CheckoutRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for CheckoutRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs
index 8bfbe8b695a..497cf81918e 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/router/src/connector/coinbase.rs
@@ -52,8 +52,7 @@ where
&self,
req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError>
- {
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index b8f398a0d96..baea07faa60 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -19,19 +19,12 @@ pub struct CryptopayRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for CryptopayRouterData<T>
-{
+impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for CryptopayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (
&types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index d93a9405ae3..1a85498ad06 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -233,8 +233,7 @@ where
&self,
req: &types::RouterData<Flow, Request, Response>,
connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError>
- {
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let date = OffsetDateTime::now_utc();
let cybersource_req = self.get_request_body(req, connectors)?;
let auth = cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?;
@@ -740,8 +739,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
&self,
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError>
- {
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -837,12 +835,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
{
Ok(format!(
"{}risk/v1/authentication-setups",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
} else {
Ok(format!(
"{}pts/v2/payments/",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
}
@@ -1111,7 +1109,7 @@ impl
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 8251de8ca31..545ee672ed9 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -38,22 +38,10 @@ pub struct CybersourceRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for CybersourceRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, 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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
// This conversion function is used at different places in the file, if updating this, keep a check for those
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
@@ -570,7 +558,7 @@ impl
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
- Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) => {
+ Some(payments::MandateReferenceId::ConnectorMandateId(_)) => {
let original_amount = item
.router_data
.get_recurring_mandate_payment_data()?
@@ -587,7 +575,7 @@ impl
merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
reason: None,
original_authorized_amount: Some(utils::get_amount_as_string(
- &types::api::CurrencyUnit::Base,
+ &api::CurrencyUnit::Base,
original_amount,
original_currency,
)?),
@@ -596,9 +584,7 @@ impl
}),
)
}
- Some(api_models::payments::MandateReferenceId::NetworkMandateId(
- network_transaction_id,
- )) => {
+ Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
let (original_amount, original_currency) = match network
.clone()
.map(|network| network.to_lowercase())
diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs
index c92c6b8b854..dc99619e9da 100644
--- a/crates/router/src/connector/dlocal.rs
+++ b/crates/router/src/connector/dlocal.rs
@@ -56,8 +56,7 @@ where
&self,
req: &types::RouterData<Flow, Request, Response>,
connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError>
- {
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let dlocal_req = self.get_request_body(req, connectors)?;
let date = date_time::date_as_yyyymmddthhmmssmmmz()
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index 14337ca0765..c073dc03cc9 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -57,20 +57,13 @@ pub struct DlocalRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for DlocalRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, 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,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index fcb808c6700..3d40876c353 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -18,20 +18,13 @@ pub struct FiservRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for FiservRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, 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,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index cfb822715bf..478da2cf902 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -269,7 +269,7 @@ impl<F, T>
})
.transpose()?;
let redirection_data =
- redirect_url.map(|url| services::RedirectForm::from((url, services::Method::Get)));
+ redirect_url.map(|url| RedirectForm::from((url, services::Method::Get)));
Ok(Self {
status,
response: get_payment_response(status, item.response, redirection_data),
@@ -434,8 +434,8 @@ fn get_mandate_details(item: &types::PaymentsAuthorizeRouterData) -> Result<Mand
Some(StoredCredential {
model: Some(requests::Model::Recurring),
sequence: Some(match connector_mandate_id.is_some() {
- true => requests::Sequence::Subsequent,
- false => requests::Sequence::First,
+ true => Sequence::Subsequent,
+ false => Sequence::First,
}),
}),
connector_mandate_id,
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index 59177307f22..e05f1b469ac 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -24,22 +24,10 @@ pub struct GocardlessRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for GocardlessRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for GocardlessRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -736,7 +724,7 @@ impl<F>
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.payments.id),
+ resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: None,
mandate_reference: Some(mandate_reference),
connector_metadata: None,
@@ -771,7 +759,7 @@ impl<F>
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.payments.id),
+ resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs
index 2dc44c8a19b..655d8a8663b 100644
--- a/crates/router/src/connector/helcim/transformers.rs
+++ b/crates/router/src/connector/helcim/transformers.rs
@@ -19,22 +19,10 @@ pub struct HelcimRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for HelcimRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for HelcimRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
@@ -45,9 +33,9 @@ impl<T>
}
pub fn check_currency(
- currency: types::storage::enums::Currency,
-) -> Result<types::storage::enums::Currency, errors::ConnectorError> {
- if currency == types::storage::enums::Currency::USD {
+ currency: enums::Currency,
+) -> Result<enums::Currency, errors::ConnectorError> {
+ if currency == enums::Currency::USD {
Ok(currency)
} else {
Err(errors::ConnectorError::NotSupported {
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 8e45b96e69c..bce25a76429 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -37,22 +37,10 @@ pub struct IatapayRouterData<T> {
amount: f64,
router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for IatapayRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for IatapayRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount: connector_util::get_amount_as_f64(currency_unit, amount, currency)?,
@@ -114,7 +102,7 @@ impl
TryFrom<
&IatapayRouterData<
&types::RouterData<
- types::api::payments::Authorize,
+ api::payments::Authorize,
PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
@@ -126,7 +114,7 @@ impl
fn try_from(
item: &IatapayRouterData<
&types::RouterData<
- types::api::payments::Authorize,
+ api::payments::Authorize,
PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 29dccfbf32b..db77b9c30cd 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -14,20 +14,13 @@ pub struct KlarnaRouterData<T> {
router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for KlarnaRouterData<T>
-{
+impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for KlarnaRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, router_data): (
&types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 850bd058e41..f993928d94f 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -20,23 +20,11 @@ pub struct MultisafepayRouterData<T> {
router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for MultisafepayRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for MultisafepayRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -677,9 +665,8 @@ impl<F, T>
MultisafepayPaymentStatus::Declined
};
- let status = enums::AttemptStatus::from(
- payment_response.data.status.unwrap_or(default_status),
- );
+ let status =
+ AttemptStatus::from(payment_response.data.status.unwrap_or(default_status));
Ok(Self {
status,
diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs
index 7c95578bfd6..4bf61ce1ca4 100644
--- a/crates/router/src/connector/netcetera/transformers.rs
+++ b/crates/router/src/connector/netcetera/transformers.rs
@@ -16,18 +16,13 @@ pub struct NetceteraRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for NetceteraRouterData<T>
+impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)>
+ for NetceteraRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (
- &types::api::CurrencyUnit,
+ &api::CurrencyUnit,
types::storage::enums::Currency,
i64,
T,
diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs
index 1370fcf11cd..88aa149a267 100644
--- a/crates/router/src/connector/nexinets.rs
+++ b/crates/router/src/connector/nexinets.rs
@@ -120,7 +120,7 @@ impl ConnectorCommon for Nexinets {
if !field.is_empty() {
msg.push_str(format!("{} : {}", field, error.message).as_str());
} else {
- msg = error.message.to_owned();
+ error.message.clone_into(&mut msg)
}
if message.is_empty() {
message.push_str(&msg);
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index ea61782d498..fdc65963fe8 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -42,11 +42,11 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
public_key: None,
}),
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
public_key: Some(key1.to_owned()),
}),
@@ -61,20 +61,13 @@ pub struct NmiRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for NmiRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for NmiRouterData<T> {
type Error = Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, currency, amount, router_data): (
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs
index aa4157a68d8..d08820266c3 100644
--- a/crates/router/src/connector/nuvei.rs
+++ b/crates/router/src/connector/nuvei.rs
@@ -161,7 +161,7 @@ impl
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/payment.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
@@ -248,7 +248,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/voidTransaction.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -334,7 +334,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/getPaymentStatus.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -417,7 +417,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/settleTransaction.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -509,7 +509,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/payment.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -671,7 +671,7 @@ impl
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/getSessionToken.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -756,7 +756,7 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/initPayment.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -839,7 +839,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/refundTransaction.do",
- api::ConnectorCommon::base_url(self, connectors)
+ ConnectorCommon::base_url(self, connectors)
))
}
@@ -954,7 +954,7 @@ impl api::IncomingWebhook for Nuvei {
serde_urlencoded::from_str::<nuvei::NuveiWebhookTransactionId>(&request.query_params)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
- types::api::PaymentIdType::ConnectorTransactionId(body.ppp_transaction_id),
+ api::PaymentIdType::ConnectorTransactionId(body.ppp_transaction_id),
))
}
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index 3267caf60d6..09da5fc8f94 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -16,20 +16,13 @@ pub struct OpennodeRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for OpennodeRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for OpennodeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, router_data): (
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 0ceed1390be..a8442f7ea8a 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -15,20 +15,13 @@ pub struct PayeezyRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for PayeezyRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for PayeezyRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, router_data): (
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ &api::CurrencyUnit,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 7f5e30402d6..0b3f4fb48ce 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -29,22 +29,10 @@ pub struct PaymeRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for PaymeRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for PaymeRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -630,7 +618,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(req_card) => {
+ PaymentMethodData::Card(req_card) => {
let card = PaymeCard {
credit_card_cvv: req_card.card_cvc.clone(),
credit_card_exp: req_card
@@ -652,23 +640,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest {
language: LANGUAGE.to_string(),
})
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("payme"),
- ))?
- }
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("payme"),
+ ))?,
}
}
}
@@ -681,7 +667,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- Some(domain::PaymentMethodData::Card(_)) => {
+ Some(PaymentMethodData::Card(_)) => {
let buyer_email = item.request.get_email()?;
let buyer_name = item.get_billing_address()?.get_full_name()?;
@@ -712,19 +698,19 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
meta_data_jwt: Secret::new(jwt_data.meta_data),
})
}
- Some(domain::PaymentMethodData::CardRedirect(_))
- | Some(domain::PaymentMethodData::Wallet(_))
- | Some(domain::PaymentMethodData::PayLater(_))
- | Some(domain::PaymentMethodData::BankRedirect(_))
- | Some(domain::PaymentMethodData::BankDebit(_))
- | Some(domain::PaymentMethodData::BankTransfer(_))
- | Some(domain::PaymentMethodData::Crypto(_))
- | Some(domain::PaymentMethodData::MandatePayment)
- | Some(domain::PaymentMethodData::Reward)
- | Some(domain::PaymentMethodData::Upi(_))
- | Some(domain::PaymentMethodData::Voucher(_))
- | Some(domain::PaymentMethodData::GiftCard(_))
- | Some(domain::PaymentMethodData::CardToken(_))
+ Some(PaymentMethodData::CardRedirect(_))
+ | Some(PaymentMethodData::Wallet(_))
+ | Some(PaymentMethodData::PayLater(_))
+ | Some(PaymentMethodData::BankRedirect(_))
+ | Some(PaymentMethodData::BankDebit(_))
+ | Some(PaymentMethodData::BankTransfer(_))
+ | Some(PaymentMethodData::Crypto(_))
+ | Some(PaymentMethodData::MandatePayment)
+ | Some(PaymentMethodData::Reward)
+ | Some(PaymentMethodData::Upi(_))
+ | Some(PaymentMethodData::Voucher(_))
+ | Some(PaymentMethodData::GiftCard(_))
+ | Some(PaymentMethodData::CardToken(_))
| None => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
@@ -736,7 +722,7 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(req_card) => {
+ PaymentMethodData::Card(req_card) => {
let seller_payme_id =
PaymeAuthType::try_from(&item.connector_auth_type)?.seller_payme_id;
let card = PaymeCard {
@@ -750,19 +736,19 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest {
seller_payme_id,
})
}
- domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::CardToken(_) => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
}
@@ -1151,14 +1137,14 @@ impl<F, T>
fn get_services(item: &types::PaymentsPreProcessingRouterData) -> Option<ThreeDs> {
match item.auth_type {
- api_models::enums::AuthenticationType::ThreeDs => {
+ AuthenticationType::ThreeDs => {
let settings = ThreeDsSettings { active: true };
Some(ThreeDs {
name: ThreeDsType::ThreeDs,
settings,
})
}
- api_models::enums::AuthenticationType::NoThreeDs => None,
+ AuthenticationType::NoThreeDs => None,
}
}
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index 63912391787..cf81fec6341 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -960,8 +960,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
) -> CustomResult<String, errors::ConnectorError> {
let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?;
match req.payment_method {
- diesel_models::enums::PaymentMethod::Wallet
- | diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!(
+ enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => Ok(format!(
"{}v2/checkout/orders/{}",
self.base_url(connectors),
req.request
@@ -1633,9 +1632,9 @@ impl services::ConnectorRedirectResponse for Paypal {
action: PaymentAction,
) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ PaymentAction::PSync
+ | PaymentAction::CompleteAuthorize
+ | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(payments::CallConnectorAction::Trigger)
}
}
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 21b0f04af86..338b8c5ba4e 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -29,18 +29,13 @@ pub struct PaypalRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for PaypalRouterData<T>
+impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)>
+ for PaypalRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (
- &types::api::CurrencyUnit,
+ &api::CurrencyUnit,
types::storage::enums::Currency,
i64,
T,
@@ -153,7 +148,7 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetail
pub struct Address {
address_line_1: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
- country_code: api_models::enums::CountryAlpha2,
+ country_code: enums::CountryAlpha2,
admin_area_2: Option<String>,
}
@@ -216,7 +211,7 @@ pub enum ThreeDsType {
#[derive(Debug, Serialize)]
pub struct RedirectRequest {
name: Secret<String>,
- country_code: api_models::enums::CountryAlpha2,
+ country_code: enums::CountryAlpha2,
experience_context: ContextStruct,
}
@@ -454,12 +449,12 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
let expiry = Some(card.get_expiry_date_as_yyyymm("-"));
let attributes = match item.router_data.auth_type {
- api_models::enums::AuthenticationType::ThreeDs => Some(ThreeDsSetting {
+ enums::AuthenticationType::ThreeDs => Some(ThreeDsSetting {
verification: ThreeDsMethod {
method: ThreeDsType::ScaAlways,
},
}),
- api_models::enums::AuthenticationType::NoThreeDs => None,
+ enums::AuthenticationType::NoThreeDs => None,
};
let payment_source = Some(PaymentSourceItem::Card(CardRequest {
@@ -858,13 +853,13 @@ impl TryFrom<&ConnectorAuthType> for PaypalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails(
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails(
PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
}),
)),
- types::ConnectorAuthType::SignatureKey {
+ ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -875,7 +870,7 @@ impl TryFrom<&ConnectorAuthType> for PaypalAuthType {
payer_id: api_secret.to_owned(),
}),
)),
- types::ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth),
+ ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
@@ -1216,7 +1211,7 @@ fn get_redirect_url(
let mut link: Option<Url> = None;
for item2 in link_vec.iter() {
if item2.rel == "payer-action" {
- link = item2.href.clone();
+ link.clone_from(&item2.href)
}
}
Ok(link)
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index 6ad3d3c2039..e400dc9b399 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -20,18 +20,13 @@ pub struct PlacetopayRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for PlacetopayRouterData<T>
+impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)>
+ for PlacetopayRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (
- &types::api::CurrencyUnit,
+ &api::CurrencyUnit,
types::storage::enums::Currency,
i64,
T,
diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs
index 570bf8d2b3a..7a8cd6e14d0 100644
--- a/crates/router/src/connector/prophetpay/transformers.rs
+++ b/crates/router/src/connector/prophetpay/transformers.rs
@@ -19,22 +19,10 @@ pub struct ProphetpayRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for ProphetpayRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ProphetpayRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
@@ -229,7 +217,7 @@ fn get_redirect_url_form(
mut redirect_url: Url,
complete_auth_url: Option<String>,
) -> CustomResult<services::RedirectForm, errors::ConnectorError> {
- let mut form_fields = std::collections::HashMap::<String, String>::new();
+ let mut form_fields = HashMap::<String, String>::new();
form_fields.insert(
String::from("redirectUrl"),
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index c5f92c20f5c..5d4579fffa7 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -652,7 +652,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
}
fn get_content_type(&self) -> &'static str {
- api::ConnectorCommon::common_get_content_type(self)
+ ConnectorCommon::common_get_content_type(self)
}
fn get_url(
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 04dc4496b62..22e1074802d 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -19,22 +19,10 @@ pub struct RapydRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for RapydRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for RapydRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs
index e11a79cb027..e7487e795b6 100644
--- a/crates/router/src/connector/shift4.rs
+++ b/crates/router/src/connector/shift4.rs
@@ -217,8 +217,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
router_data: &mut types::PaymentsAuthorizeRouterData,
app_state: &routes::AppState,
) -> CustomResult<(), errors::ConnectorError> {
- if router_data.auth_type == diesel_models::enums::AuthenticationType::ThreeDs
- && router_data.payment_method == diesel_models::enums::PaymentMethod::Card
+ if router_data.auth_type == enums::AuthenticationType::ThreeDs
+ && router_data.payment_method == enums::PaymentMethod::Card
{
let integ: Box<
&(dyn ConnectorIntegration<
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 92a72f42d1e..30f327c700e 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -747,9 +747,9 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for Shift4RefundRequest {
impl From<Shift4RefundStatus> for enums::RefundStatus {
fn from(item: Shift4RefundStatus) -> Self {
match item {
- self::Shift4RefundStatus::Successful => Self::Success,
- self::Shift4RefundStatus::Failed => Self::Failure,
- self::Shift4RefundStatus::Processing => Self::Pending,
+ Shift4RefundStatus::Successful => Self::Success,
+ Shift4RefundStatus::Failed => Self::Failure,
+ Shift4RefundStatus::Processing => Self::Pending,
}
}
}
diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs
index 550e1ae30a8..1c045b8da01 100644
--- a/crates/router/src/connector/signifyd.rs
+++ b/crates/router/src/connector/signifyd.rs
@@ -94,7 +94,7 @@ impl ConnectorCommon for Signifyd {
Ok(ErrorResponse {
status_code: res.status_code,
- code: crate::consts::NO_ERROR_CODE.to_string(),
+ code: consts::NO_ERROR_CODE.to_string(),
message: response.messages.join(" &"),
reason: Some(response.errors.to_string()),
attempt_status: None,
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 318e33978cc..c980a4e7494 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -5,10 +5,7 @@ use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData},
core::errors,
- types::{
- self, api, domain,
- storage::{self, enums},
- },
+ types::{self, api, domain, storage::enums},
unimplemented_payment_method,
};
@@ -199,7 +196,7 @@ impl<F, T>
item: types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- status: storage::enums::AttemptStatus::Pending,
+ status: enums::AttemptStatus::Pending,
session_token: Some(item.response.session_id.clone().expose()),
response: Ok(types::PaymentsResponseData::SessionTokenResponse {
session_token: item.response.session_id.expose(),
diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs
index c923ca0577d..4604e9da872 100644
--- a/crates/router/src/connector/stax.rs
+++ b/crates/router/src/connector/stax.rs
@@ -869,29 +869,25 @@ impl api::IncomingWebhook for Stax {
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match webhook_body.transaction_type {
- stax::StaxWebhookEventType::Refund => {
- Ok(api_models::webhooks::ObjectReferenceId::RefundId(
- api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.id),
- ))
- }
- stax::StaxWebhookEventType::Unknown => {
+ StaxWebhookEventType::Refund => Ok(api_models::webhooks::ObjectReferenceId::RefundId(
+ api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.id),
+ )),
+ StaxWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
- stax::StaxWebhookEventType::PreAuth
- | stax::StaxWebhookEventType::Capture
- | stax::StaxWebhookEventType::Charge
- | stax::StaxWebhookEventType::Void => {
- Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
- api_models::payments::PaymentIdType::ConnectorTransactionId(match webhook_body
- .transaction_type
- {
- stax::StaxWebhookEventType::Capture => webhook_body
+ StaxWebhookEventType::PreAuth
+ | StaxWebhookEventType::Capture
+ | StaxWebhookEventType::Charge
+ | StaxWebhookEventType::Void => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(
+ match webhook_body.transaction_type {
+ StaxWebhookEventType::Capture => webhook_body
.auth_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
_ => webhook_body.id,
- }),
- ))
- }
+ },
+ ),
+ )),
}
}
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 1d097c40e7f..d48a2b1e82b 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -18,22 +18,10 @@ pub struct StaxRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for StaxRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for StaxRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 64789e176fc..724a0ea6f78 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -2274,7 +2274,7 @@ impl services::ConnectorRedirectResponse for Stripe {
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: services::PaymentAction,
- ) -> CustomResult<crate::core::payments::CallConnectorAction, errors::ConnectorError> {
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
match action {
services::PaymentAction::PSync
| services::PaymentAction::CompleteAuthorize
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 6932f6b7495..6b82c87b5d1 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1107,9 +1107,7 @@ impl TryFrom<(&domain::BankRedirectData, Option<bool>)> for StripeBillingAddress
},
)?;
Self {
- name: Some(connector_util::BankRedirectBillingData::get_billing_name(
- &billing_data,
- )?),
+ name: Some(BankRedirectBillingData::get_billing_name(&billing_data)?),
..Self::default()
}
}),
@@ -2859,16 +2857,14 @@ impl Serialize for StripeNextActionResponse {
{
match *self {
Self::CashappHandleRedirectOrDisplayQrCode(ref i) => {
- serde::Serialize::serialize(i, serializer)
- }
- Self::RedirectToUrl(ref i) => serde::Serialize::serialize(i, serializer),
- Self::AlipayHandleRedirect(ref i) => serde::Serialize::serialize(i, serializer),
- Self::VerifyWithMicrodeposits(ref i) => serde::Serialize::serialize(i, serializer),
- Self::WechatPayDisplayQrCode(ref i) => serde::Serialize::serialize(i, serializer),
- Self::DisplayBankTransferInstructions(ref i) => {
- serde::Serialize::serialize(i, serializer)
+ Serialize::serialize(i, serializer)
}
- Self::NoNextActionBody => serde::Serialize::serialize("NoNextActionBody", serializer),
+ Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer),
+ Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer),
+ Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer),
+ Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer),
+ Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer),
+ Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer),
}
}
}
@@ -2984,10 +2980,10 @@ pub enum RefundStatus {
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
- self::RefundStatus::Succeeded => Self::Success,
- self::RefundStatus::Failed => Self::Failure,
- self::RefundStatus::Pending => Self::Pending,
- self::RefundStatus::RequiresAction => Self::ManualReview,
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Pending => Self::Pending,
+ RefundStatus::RequiresAction => Self::ManualReview,
}
}
}
@@ -3382,12 +3378,12 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme
code: item
.response
.failure_code
- .unwrap_or_else(|| crate::consts::NO_ERROR_CODE.to_string()),
+ .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: item
.response
.failure_message
.clone()
- .unwrap_or_else(|| crate::consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_message,
status_code: item.http_code,
attempt_status: Some(status),
diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs
index f0a2f116a40..d6a77fef31e 100644
--- a/crates/router/src/connector/threedsecureio/transformers.rs
+++ b/crates/router/src/connector/threedsecureio/transformers.rs
@@ -27,18 +27,13 @@ pub struct ThreedsecureioRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for ThreedsecureioRouterData<T>
+impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)>
+ for ThreedsecureioRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (
- &types::api::CurrencyUnit,
+ &api::CurrencyUnit,
types::storage::enums::Currency,
i64,
T,
@@ -168,7 +163,7 @@ impl
let creq_str = to_string(&creq)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing creq_str")?;
- let creq_base64 = base64::Engine::encode(&BASE64_ENGINE, creq_str)
+ let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str)
.trim_end_matches('=')
.to_owned();
Ok(
@@ -270,7 +265,7 @@ impl TryFrom<&ThreedsecureioRouterData<&types::authentication::ConnectorAuthenti
.map(|currency| currency.to_string())
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing field currency")?;
- let purchase_currency: Currency = iso_currency::Currency::from_code(¤cy)
+ let purchase_currency: Currency = Currency::from_code(¤cy)
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error while parsing Currency")?;
let billing_address = request.billing_address.address.clone().ok_or(
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index c40435c01bb..5a318e5e440 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -28,19 +28,12 @@ pub struct TrustpayRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for TrustpayRouterData<T>
-{
+impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for TrustpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (
&types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ enums::Currency,
i64,
T,
),
@@ -1179,7 +1172,7 @@ impl<F>
let create_intent_response = item.response.init_result_data.to_owned();
let secrets = item.response.secrets.to_owned();
let instance_id = item.response.instance_id.to_owned();
- let pmt = utils::PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?;
+ let pmt = PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?;
match (pmt, create_intent_response) {
(
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index 6ffe1f1ed7f..dfc7e61c000 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -5,10 +5,7 @@ use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RefundsRequestData},
core::errors,
- types::{
- self, api, domain,
- storage::{self, enums},
- },
+ types::{self, api, domain, storage::enums},
};
#[derive(Debug, Serialize)]
@@ -25,7 +22,7 @@ pub struct TsysPaymentAuthSaleRequest {
transaction_key: Secret<String>,
card_data_source: String,
transaction_amount: String,
- currency_code: storage::enums::Currency,
+ currency_code: enums::Currency,
card_number: cards::CardNumber,
expiration_date: Secret<String>,
cvv2: Secret<String>,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index bb52d4885fb..5a5b1242611 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -363,10 +363,7 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
}
fn is_three_ds(&self) -> bool {
- matches!(
- self.auth_type,
- diesel_models::enums::AuthenticationType::ThreeDs
- )
+ matches!(self.auth_type, enums::AuthenticationType::ThreeDs)
}
fn get_shipping_address(&self) -> Result<&api::AddressDetails, Error> {
@@ -430,8 +427,8 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
pub trait PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error>;
- fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error>;
- fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error>;
+ fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
+ fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_amount(&self) -> Result<i64, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
@@ -445,12 +442,12 @@ impl PaymentsPreProcessingData for types::PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
- fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error> {
+ fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
- fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error> {
+ fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_amount(&self) -> Result<i64, Error> {
@@ -458,8 +455,8 @@ impl PaymentsPreProcessingData for types::PaymentsPreProcessingData {
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
- Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true),
- Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false),
+ Some(enums::CaptureMethod::Automatic) | None => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
@@ -551,7 +548,7 @@ pub trait PaymentsAuthorizeRequestData {
fn get_router_return_url(&self) -> Result<String, Error>;
fn is_wallet(&self) -> bool;
fn is_card(&self) -> bool;
- fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error>;
+ fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_connector_mandate_id(&self) -> Result<String, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>;
@@ -578,8 +575,8 @@ impl PaymentMethodTokenizationRequestData for types::PaymentMethodTokenizationDa
impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
- Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true),
- Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false),
+ Some(enums::CaptureMethod::Automatic) | None => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
@@ -619,9 +616,9 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
- Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
- connector_mandate_ids,
- )) => connector_mandate_ids.connector_mandate_id.clone(),
+ Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
+ connector_mandate_ids.connector_mandate_id.clone()
+ }
_ => None,
})
}
@@ -653,7 +650,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
matches!(self.payment_method_data, domain::PaymentMethodData::Card(_))
}
- fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error> {
+ fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
@@ -797,8 +794,8 @@ pub trait PaymentsCompleteAuthorizeRequestData {
impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
- Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true),
- Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false),
+ Some(enums::CaptureMethod::Automatic) | None => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
@@ -831,8 +828,8 @@ pub trait PaymentsSyncRequestData {
impl PaymentsSyncRequestData for types::PaymentsSyncData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
- Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true),
- Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false),
+ Some(enums::CaptureMethod::Automatic) | None => Ok(true),
+ Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
@@ -910,7 +907,7 @@ impl CustomerDetails for types::CustomerDetails {
pub trait PaymentsCancelRequestData {
fn get_amount(&self) -> Result<i64, Error>;
- fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error>;
+ fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_cancellation_reason(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
@@ -919,7 +916,7 @@ impl PaymentsCancelRequestData for PaymentsCancelData {
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
- fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error> {
+ fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_cancellation_reason(&self) -> Result<String, Error> {
@@ -1540,7 +1537,7 @@ impl MandateData for payments::MandateAmountData {
pub trait RecurringMandateData {
fn get_original_payment_amount(&self) -> Result<i64, Error>;
- fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error>;
+ fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
}
impl RecurringMandateData for RecurringMandatePaymentData {
@@ -1548,7 +1545,7 @@ impl RecurringMandateData for RecurringMandatePaymentData {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
}
- fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error> {
+ fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> {
self.original_payment_authorized_currency
.ok_or_else(missing_field_err("original_payment_authorized_currency"))
}
@@ -1558,7 +1555,7 @@ pub trait MandateReferenceData {
fn get_connector_mandate_id(&self) -> Result<String, Error>;
}
-impl MandateReferenceData for api_models::payments::ConnectorMandateReferenceId {
+impl MandateReferenceData for payments::ConnectorMandateReferenceId {
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id
.clone()
@@ -1645,7 +1642,7 @@ pub fn base64_decode(data: String) -> Result<Vec<u8>, Error> {
pub fn to_currency_base_unit_from_optional_amount(
amount: Option<i64>,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
match amount {
Some(a) => to_currency_base_unit(a, currency),
@@ -1657,25 +1654,25 @@ pub fn to_currency_base_unit_from_optional_amount(
}
pub fn get_amount_as_string(
- currency_unit: &types::api::CurrencyUnit,
+ currency_unit: &api::CurrencyUnit,
amount: i64,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
- types::api::CurrencyUnit::Minor => amount.to_string(),
- types::api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
+ api::CurrencyUnit::Minor => amount.to_string(),
+ api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
};
Ok(amount)
}
pub fn get_amount_as_f64(
- currency_unit: &types::api::CurrencyUnit,
+ currency_unit: &api::CurrencyUnit,
amount: i64,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
- types::api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?,
- types::api::CurrencyUnit::Minor => u32::try_from(amount)
+ api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?,
+ api::CurrencyUnit::Minor => u32::try_from(amount)
.change_context(errors::ConnectorError::ParsingFailed)?
.into(),
};
@@ -1684,7 +1681,7 @@ pub fn get_amount_as_f64(
pub fn to_currency_base_unit(
amount: i64,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit(amount)
@@ -1693,7 +1690,7 @@ pub fn to_currency_base_unit(
pub fn to_currency_lower_unit(
amount: String,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_lower_unit(amount)
@@ -1721,7 +1718,7 @@ pub fn construct_not_supported_error_report(
pub fn to_currency_base_unit_with_zero_decimal_check(
amount: i64,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_with_zero_decimal_check(amount)
@@ -1730,7 +1727,7 @@ pub fn to_currency_base_unit_with_zero_decimal_check(
pub fn to_currency_base_unit_asf64(
amount: i64,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_asf64(amount)
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index d3913296c09..814eefaf5ff 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -18,18 +18,13 @@ pub struct VoltRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for VoltRouterData<T>
+impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)>
+ for VoltRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (
- &types::api::CurrencyUnit,
+ &api::CurrencyUnit,
types::storage::enums::Currency,
i64,
T,
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 3dba5ea24e7..795133f602f 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -190,22 +190,10 @@ pub struct WorldlineRouterData<T> {
amount: i64,
router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for WorldlineRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for WorldlineRouterData<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,
- ),
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -218,7 +206,7 @@ impl
TryFrom<
&WorldlineRouterData<
&types::RouterData<
- types::api::payments::Authorize,
+ api::payments::Authorize,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
@@ -230,7 +218,7 @@ impl
fn try_from(
item: &WorldlineRouterData<
&types::RouterData<
- types::api::payments::Authorize,
+ api::payments::Authorize,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
@@ -593,7 +581,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData
item.response.status,
item.response.capture_method,
)),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
+ response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
@@ -645,7 +633,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp
item.response.payment.status,
item.response.payment.capture_method,
)),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
+ response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payment.id.clone(),
),
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 1f2dac807d1..894cfc16331 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -750,9 +750,7 @@ impl api::IncomingWebhook for Worldpay {
.parse_struct("WorldpayWebhookTransactionId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
- types::api::PaymentIdType::ConnectorTransactionId(
- body.event_details.transaction_reference,
- ),
+ api::PaymentIdType::ConnectorTransactionId(body.event_details.transaction_reference),
))
}
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 35a2f8cee8a..9c908cf749d 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -244,7 +244,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>>
})?,
},
description: item.response.description,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
+ response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::try_from(item.response.links)?,
redirection_data: None,
mandate_reference: None,
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index ead716af721..67538b819d5 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -23,22 +23,10 @@ pub struct ZenRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for ZenRouterData<T>
-{
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ZenRouterData<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,
- ),
+ (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs
index 3ffd5b2ccef..58ff6ab2fab 100644
--- a/crates/router/src/connector/zsl/transformers.rs
+++ b/crates/router/src/connector/zsl/transformers.rs
@@ -27,19 +27,12 @@ pub struct ZslRouterData<T> {
pub router_data: T,
}
-impl<T>
- TryFrom<(
- &types::api::CurrencyUnit,
- types::storage::enums::Currency,
- i64,
- T,
- )> for ZslRouterData<T>
-{
+impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for ZslRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, txn_amount, item): (
&types::api::CurrencyUnit,
- types::storage::enums::Currency,
+ enums::Currency,
i64,
T,
),
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 0b8d52332d9..ee06097a599 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -268,7 +268,7 @@ pub async fn create_merchant_account(
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
- db.insert_config(diesel_models::configs::ConfigNew {
+ db.insert_config(configs::ConfigNew {
key: format!("{}_requires_cvv", merchant_account.merchant_id),
config: "true".to_string(),
})
@@ -545,7 +545,7 @@ pub async fn merchant_account_update(
let updated_merchant_account = storage::MerchantAccountUpdate::Update {
merchant_name: req
.merchant_name
- .map(masking::Secret::new)
+ .map(Secret::new)
.async_lift(|inner| domain_types::encrypt_optional(inner, key))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -554,11 +554,11 @@ pub async fn merchant_account_update(
merchant_details: req
.merchant_details
.as_ref()
- .map(utils::Encode::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to convert merchant_details to a value")?
- .map(masking::Secret::new)
+ .map(Secret::new)
.async_lift(|inner| domain_types::encrypt_optional(inner, key))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -569,7 +569,7 @@ pub async fn merchant_account_update(
webhook_details: req
.webhook_details
.as_ref()
- .map(utils::Encode::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
@@ -941,8 +941,8 @@ pub async fn create_payment_connector(
business_country: req.business_country,
business_label: req.business_label.clone(),
business_sub_label: req.business_sub_label.clone(),
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
+ created_at: date_time::now(),
+ modified_at: date_time::now(),
id: None,
connector_webhook_details: match req.connector_webhook_details {
Some(connector_webhook_details) => {
@@ -951,7 +951,7 @@ pub async fn create_payment_connector(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {}", merchant_id))
.map(Some)?
- .map(masking::Secret::new)
+ .map(Secret::new)
}
None => None,
},
@@ -1278,7 +1278,7 @@ pub async fn update_payment_connector(
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(Some)?
- .map(masking::Secret::new),
+ .map(Secret::new),
None => None,
},
applepay_verified_domains: None,
@@ -1458,7 +1458,7 @@ pub fn get_frm_config_as_secret(
config
.encode_to_value()
.change_context(errors::ApiErrorResponse::ConfigNotFound)
- .map(masking::Secret::new)
+ .map(Secret::new)
})
.collect::<Result<Vec<_>, _>>()
.ok()?;
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index f75ed011688..7f2b343b968 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -184,7 +184,7 @@ pub async fn add_api_key_expiry_task(
api_key: &ApiKey,
expiry_reminder_days: Vec<u8>,
) -> Result<(), errors::ProcessTrackerError> {
- let current_time = common_utils::date_time::now();
+ let current_time = date_time::now();
let schedule_time = expiry_reminder_days
.first()
@@ -341,7 +341,7 @@ pub async fn update_api_key_expiry_task(
api_key: &ApiKey,
expiry_reminder_days: Vec<u8>,
) -> Result<(), errors::ProcessTrackerError> {
- let current_time = common_utils::date_time::now();
+ let current_time = date_time::now();
let schedule_time = expiry_reminder_days
.first()
diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs
index 36ee3c20416..e2f605304a7 100644
--- a/crates/router/src/core/authentication.rs
+++ b/crates/router/src/core/authentication.rs
@@ -9,7 +9,7 @@ use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use masking::ExposeInterface;
-use super::errors::{self, StorageErrorExt};
+use super::errors::StorageErrorExt;
use crate::{
core::{errors::ApiErrorResponse, payments as payments_core},
routes::AppState,
@@ -23,10 +23,10 @@ pub async fn perform_authentication(
authentication_connector: String,
payment_method_data: payments::PaymentMethodData,
payment_method: common_enums::PaymentMethod,
- billing_address: api_models::payments::Address,
- shipping_address: Option<api_models::payments::Address>,
+ billing_address: payments::Address,
+ shipping_address: Option<payments::Address>,
browser_details: Option<core_types::BrowserInformation>,
- business_profile: core_types::storage::BusinessProfile,
+ business_profile: storage::BusinessProfile,
merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,
amount: Option<i64>,
currency: Option<Currency>,
@@ -35,10 +35,10 @@ pub async fn perform_authentication(
authentication_data: storage::Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
- threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
+ threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
-) -> CustomResult<core_types::api::authentication::AuthenticationResponse, ApiErrorResponse> {
+) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> {
let router_data = transformers::construct_authentication_router_data(
authentication_connector.clone(),
payment_method_data,
@@ -72,13 +72,13 @@ pub async fn perform_authentication(
status_code: err.status_code,
reason: err.reason,
})?;
- core_types::api::authentication::AuthenticationResponse::try_from(authentication)
+ api::authentication::AuthenticationResponse::try_from(authentication)
}
pub async fn perform_post_authentication(
state: &AppState,
key_store: &domain::MerchantKeyStore,
- business_profile: core_types::storage::BusinessProfile,
+ business_profile: storage::BusinessProfile,
authentication_id: String,
) -> CustomResult<storage::Authentication, ApiErrorResponse> {
let (authentication_connector, three_ds_connector_account) =
@@ -96,7 +96,7 @@ pub async fn perform_post_authentication(
authentication_id.clone(),
)
.await
- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .to_not_found_response(ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}"))?;
if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled {
let router_data = transformers::construct_post_authentication_router_data(
@@ -119,7 +119,7 @@ pub async fn perform_pre_authentication(
key_store: &domain::MerchantKeyStore,
card_number: cards::CardNumber,
token: String,
- business_profile: &core_types::storage::BusinessProfile,
+ business_profile: &storage::BusinessProfile,
acquirer_details: Option<types::AcquirerDetails>,
payment_id: Option<String>,
) -> CustomResult<storage::Authentication, ApiErrorResponse> {
@@ -135,7 +135,7 @@ pub async fn perform_pre_authentication(
payment_id,
three_ds_connector_account
.get_mca_id()
- .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding mca_id from merchant_connector_account")?,
)
.await?;
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index d4cad2fbedb..9e00dfe70c9 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -29,8 +29,8 @@ pub fn construct_authentication_router_data(
authentication_connector: String,
payment_method_data: payments::PaymentMethodData,
payment_method: PaymentMethod,
- billing_address: api_models::payments::Address,
- shipping_address: Option<api_models::payments::Address>,
+ billing_address: payments::Address,
+ shipping_address: Option<payments::Address>,
browser_details: Option<types::BrowserInformation>,
amount: Option<i64>,
currency: Option<common_enums::Currency>,
@@ -40,8 +40,8 @@ pub fn construct_authentication_router_data(
merchant_connector_account: payments_helpers::MerchantConnectorAccountType,
authentication_data: storage::Authentication,
return_url: Option<String>,
- sdk_information: Option<api_models::payments::SdkInformation>,
- threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
+ sdk_information: Option<payments::SdkInformation>,
+ threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> {
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index af97c500f3e..3b10b408f9e 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -37,7 +37,7 @@ pub async fn create_customer(
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();
+ merchant_id.clone_into(&mut customer_data.merchant_id);
// We first need to validate whether the customer with the given customer id already exists
// this may seem like a redundant db call, as the insert_customer will anyway return this error
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index d80d86460b2..a70a97e7bf0 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -105,7 +105,7 @@ impl From<ring::error::Unspecified> for EncryptionError {
pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> {
ApiErrorResponse::NotImplemented {
- message: api_error_response::NotImplementedMessage::Default,
+ message: NotImplementedMessage::Default,
}
.error_response()
}
diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs
index e2ce5b42c3f..5dedcb14863 100644
--- a/crates/router/src/core/files.rs
+++ b/crates/router/src/core/files.rs
@@ -7,7 +7,7 @@ use super::errors::{self, RouterResponse};
use crate::{
consts,
routes::AppState,
- services::{self, ApplicationResponse},
+ services::ApplicationResponse,
types::{api, domain},
};
@@ -72,9 +72,9 @@ pub async fn files_create_core(
.attach_printable_lazy(|| {
format!("Unable to update file_metadata with file_id: {}", file_id)
})?;
- Ok(services::api::ApplicationResponse::Json(
- files::CreateFileResponse { file_id },
- ))
+ Ok(ApplicationResponse::Json(files::CreateFileResponse {
+ file_id,
+ }))
}
pub async fn files_delete_core(
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 5e03033977e..e26d5d0b461 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -81,10 +81,10 @@ where
)
.await?;
- frm_data.payment_attempt.connector_transaction_id = payment_data
+ frm_data
.payment_attempt
.connector_transaction_id
- .clone();
+ .clone_from(&payment_data.payment_attempt.connector_transaction_id);
let mut router_data = frm_data
.construct_router_data(
@@ -676,7 +676,7 @@ where
if matches!(fraud_capture_method, Some(Some(CaptureMethod::Manual)))
&& matches!(
payment_data.payment_attempt.status,
- api_models::enums::AttemptStatus::Unresolved
+ AttemptStatus::Unresolved
)
{
if let Some(info) = frm_info {
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index 939367bd4db..7a1e294f9dc 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -512,11 +512,11 @@ impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
pub trait MandateBehaviour {
fn get_amount(&self) -> i64;
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage>;
- fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds>;
- fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>);
+ fn get_mandate_id(&self) -> Option<&payments::MandateIds>;
+ fn set_mandate_id(&mut self, new_mandate_id: Option<payments::MandateIds>);
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData;
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData>;
- fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>;
+ fn get_customer_acceptance(&self) -> Option<payments::CustomerAcceptance>;
}
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index 3f9f5f017a7..11c53a77b1e 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -350,7 +350,9 @@ fn validate_order_details(
order_details_amount_string.product_img_link =
Some(DEFAULT_PRODUCT_IMG.to_string())
} else {
- order_details_amount_string.product_img_link = order.product_img_link.clone()
+ order_details_amount_string
+ .product_img_link
+ .clone_from(&order.product_img_link)
};
order_details_amount_string.amount =
currency
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d3f6aeea24b..9ae327269cf 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -115,10 +115,10 @@ pub async fn create_payment_method(
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
scheme: req.card_network.clone(),
- metadata: pm_metadata.map(masking::Secret::new),
+ metadata: pm_metadata.map(Secret::new),
payment_method_data,
connector_mandate_details,
- customer_acceptance: customer_acceptance.map(masking::Secret::new),
+ customer_acceptance: customer_acceptance.map(Secret::new),
client_secret: Some(client_secret),
status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
@@ -201,7 +201,7 @@ pub async fn get_or_insert_payment_method(
.await;
match &existing_pm_by_locker_id {
- Ok(pm) => payment_method_id = pm.payment_method_id.clone(),
+ Ok(pm) => payment_method_id.clone_from(&pm.payment_method_id),
Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
};
existing_pm_by_locker_id
@@ -212,7 +212,7 @@ pub async fn get_or_insert_payment_method(
existing_pm_by_pmid
}
};
- resp.payment_method_id = payment_method_id.to_owned();
+ payment_method_id.clone_into(&mut resp.payment_method_id);
match payment_method {
Ok(pm) => Ok(pm),
@@ -405,7 +405,7 @@ pub async fn add_payment_method_data(
return Ok(services::ApplicationResponse::Json(pm_resp));
} else {
let locker_id = pm_resp.payment_method_id.clone();
- pm_resp.payment_method_id = pm_id.clone();
+ pm_resp.payment_method_id.clone_from(&pm_id);
pm_resp.client_secret = Some(client_secret.clone());
let card_isin = card.card_number.clone().get_card_isin();
@@ -898,7 +898,9 @@ pub async fn update_customer_payment_method(
payment_method_data: pm_data_encrypted,
};
- add_card_resp.payment_method_id = pm.payment_method_id.clone();
+ add_card_resp
+ .payment_method_id
+ .clone_from(&pm.payment_method_id);
db.update_payment_method(pm, pm_update, merchant_account.storage_scheme)
.await
@@ -1191,7 +1193,7 @@ pub async fn add_card_hs(
card_exp_year: card.card_exp_year.to_owned(),
card_brand: card.card_network.as_ref().map(ToString::to_string),
card_isin: None,
- nick_name: card.nick_name.as_ref().map(masking::Secret::peek).cloned(),
+ nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),
},
});
@@ -2912,7 +2914,7 @@ fn filter_pm_based_on_supported_payments_for_mandate(
}
fn filter_pm_based_on_config<'a>(
- config: &'a crate::configs::settings::ConnectorFilters,
+ config: &'a settings::ConnectorFilters,
connector: &'a str,
payment_method_type: &'a api_enums::PaymentMethodType,
payment_attempt: Option<&storage::PaymentAttempt>,
@@ -3615,7 +3617,7 @@ pub async fn get_card_details_with_locker_fallback(
Ok(if let Some(mut crd) = card_decrypted {
if crd.saved_to_locker {
- crd.scheme = pm.scheme.clone();
+ crd.scheme.clone_from(&pm.scheme);
Some(crd)
} else {
None
@@ -3645,7 +3647,7 @@ pub async fn get_card_details_without_locker_fallback(
});
Ok(if let Some(mut crd) = card_decrypted {
- crd.scheme = pm.scheme.clone();
+ crd.scheme.clone_from(&pm.scheme);
crd
} else {
get_card_details_from_locker(state, pm).await?
@@ -4005,10 +4007,7 @@ impl TempLockerCardSupport {
metrics::TASKS_ADDED_COUNT.add(
&metrics::CONTEXT,
1,
- &[metrics::request::add_attributes(
- "flow",
- "DeleteTokenizeData",
- )],
+ &[request::add_attributes("flow", "DeleteTokenizeData")],
);
Ok(card)
}
@@ -4171,7 +4170,7 @@ pub async fn create_encrypted_payment_method_data(
let pm_data_encrypted: Option<Encryption> = pm_data
.as_ref()
- .map(utils::Encode::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Unable to convert payment method data to a value")
@@ -4179,7 +4178,7 @@ pub async fn create_encrypted_payment_method_data(
logger::error!(err=?err);
None
})
- .map(masking::Secret::<_, masking::WithType>::new)
+ .map(Secret::<_, masking::WithType>::new)
.async_lift(|inner| encrypt_optional(inner, key))
.await
.change_context(errors::StorageError::EncryptionError)
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 9c53642f4d7..009e9e54467 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -563,7 +563,7 @@ pub fn get_card_detail(
card_token: None,
card_fingerprint: None,
card_holder_name: response.name_on_card,
- nick_name: response.nick_name.map(masking::Secret::new),
+ nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 815c604a0e3..694e283ce2f 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -12,8 +12,10 @@ pub mod transformers;
pub mod types;
#[cfg(feature = "olap")]
-use std::collections::{HashMap, HashSet};
-use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter};
+use std::collections::HashMap;
+use std::{
+ collections::HashSet, fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter,
+};
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
@@ -119,7 +121,7 @@ where
router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
- dyn router_types::api::Connector:
+ dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
@@ -265,7 +267,7 @@ where
_ => (),
};
payment_data = match connector_details {
- api::ConnectorCallType::PreDetermined(connector) => {
+ ConnectorCallType::PreDetermined(connector) => {
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
@@ -329,7 +331,7 @@ where
.await?
}
- api::ConnectorCallType::Retryable(connectors) => {
+ ConnectorCallType::Retryable(connectors) => {
let mut connectors = connectors.into_iter();
let connector_data = get_connector_data(&mut connectors)?;
@@ -430,7 +432,7 @@ where
.await?
}
- api::ConnectorCallType::SessionMultiple(connectors) => {
+ ConnectorCallType::SessionMultiple(connectors) => {
let session_surcharge_details =
call_surcharge_decision_management_for_session_flow(
state,
@@ -739,7 +741,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, Ctx>(
req: Req,
auth_flow: services::AuthFlow,
call_connector_action: CallConnectorAction,
- eligible_connectors: Option<Vec<api_models::enums::Connector>>,
+ eligible_connectors: Option<Vec<enums::Connector>>,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
@@ -754,7 +756,7 @@ where
Ctx: PaymentMethodRetrieve,
// To construct connector flow specific api
- dyn router_types::api::Connector:
+ dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
@@ -992,7 +994,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCom
// If the status is requires customer action, then send the startpay url again
// The redirection data must have been provided and updated by the connector
let redirection_response = match payments_response.status {
- api_models::enums::IntentStatus::RequiresCustomerAction => {
+ enums::IntentStatus::RequiresCustomerAction => {
let startpay_url = payments_response
.next_action
.clone()
@@ -1019,9 +1021,9 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCom
})
}
// 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| api_models::enums::IntentStatus::Processing=> helpers::get_handle_response_url(
+ enums::IntentStatus::Succeeded
+ | enums::IntentStatus::Failed
+ | enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture| enums::IntentStatus::Processing=> helpers::get_handle_response_url(
payment_id,
&payment_flow_response.business_profile,
payments_response,
@@ -1291,9 +1293,8 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticat
}?;
// When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client
if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction {
- let req_poll_id =
- super::utils::get_external_authentication_request_poll_id(&payment_id);
- let poll_id = super::utils::get_poll_id(merchant_id.clone(), req_poll_id.clone());
+ let req_poll_id = utils::get_external_authentication_request_poll_id(&payment_id);
+ let poll_id = utils::get_poll_id(merchant_id.clone(), req_poll_id.clone());
let redis_conn = state
.store
.get_redis_conn()
@@ -1795,7 +1796,7 @@ where
merchant_connector_account.get_mca_id(),
)?;
- let connector_label = super::utils::get_connector_label(
+ let connector_label = utils::get_connector_label(
payment_data.payment_intent.business_country,
payment_data.payment_intent.business_label.as_ref(),
payment_data.payment_attempt.business_sub_label.as_ref(),
@@ -2085,13 +2086,11 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization(
}
fn decide_apple_pay_flow(
- payment_method_type: &Option<api_models::enums::PaymentMethodType>,
+ payment_method_type: &Option<enums::PaymentMethodType>,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
) -> Option<enums::ApplePayFlow> {
payment_method_type.and_then(|pmt| match pmt {
- api_models::enums::PaymentMethodType::ApplePay => {
- check_apple_pay_metadata(merchant_connector_account)
- }
+ enums::PaymentMethodType::ApplePay => check_apple_pay_metadata(merchant_connector_account),
_ => None,
})
}
@@ -3030,7 +3029,7 @@ pub async fn get_connector_choice<F, Req, Ctx>(
business_profile: &storage::business_profile::BusinessProfile,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
- eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<Option<ConnectorCallType>>
where
@@ -3059,7 +3058,7 @@ where
connectors,
)
.await?;
- api::ConnectorCallType::SessionMultiple(routing_output)
+ ConnectorCallType::SessionMultiple(routing_output)
}
api::ConnectorChoice::StraightThrough(straight_through) => {
@@ -3110,7 +3109,7 @@ pub async fn connector_selection<F>(
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
request_straight_through: Option<serde_json::Value>,
- eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
@@ -3186,7 +3185,7 @@ pub async fn decide_connector<F>(
payment_data: &mut PaymentData<F>,
request_straight_through: Option<api::routing::StraightThroughAlgorithm>,
routing_data: &mut storage::RoutingData,
- eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
@@ -3207,7 +3206,7 @@ where
.attach_printable("Invalid connector name received in 'routed_through'")?;
routing_data.routed_through = Some(connector_name.clone());
- return Ok(api::ConnectorCallType::PreDetermined(connector_data));
+ return Ok(ConnectorCallType::PreDetermined(connector_data));
}
if let Some(mandate_connector_details) = payment_data.mandate_connector.as_ref() {
@@ -3226,10 +3225,11 @@ where
routing_data.routed_through = Some(mandate_connector_details.connector.clone());
#[cfg(feature = "connector_choice_mca_id")]
{
- routing_data.merchant_connector_id =
- mandate_connector_details.merchant_connector_id.clone();
+ routing_data
+ .merchant_connector_id
+ .clone_from(&mandate_connector_details.merchant_connector_id);
}
- return Ok(api::ConnectorCallType::PreDetermined(connector_data));
+ return Ok(ConnectorCallType::PreDetermined(connector_data));
}
if let Some((pre_routing_results, storage_pm_type)) = routing_data
@@ -3257,13 +3257,15 @@ where
routing_data.routed_through = Some(choice.connector.to_string());
#[cfg(feature = "connector_choice_mca_id")]
{
- routing_data.merchant_connector_id = choice.merchant_connector_id.clone();
+ routing_data
+ .merchant_connector_id
+ .clone_from(&choice.merchant_connector_id);
}
#[cfg(not(feature = "connector_choice_mca_id"))]
{
routing_data.business_sub_label = choice.sub_label.clone();
}
- return Ok(api::ConnectorCallType::PreDetermined(connector_data));
+ return Ok(ConnectorCallType::PreDetermined(connector_data));
}
}
@@ -3551,14 +3553,16 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
#[cfg(feature = "connector_choice_mca_id")]
{
- routing_data.merchant_connector_id =
- chosen_connector_data.merchant_connector_id.clone();
+ routing_data
+ .merchant_connector_id
+ .clone_from(&chosen_connector_data.merchant_connector_id);
}
routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
#[cfg(feature = "connector_choice_mca_id")]
{
- routing_data.merchant_connector_id =
- chosen_connector_data.merchant_connector_id.clone();
+ routing_data
+ .merchant_connector_id
+ .clone_from(&chosen_connector_data.merchant_connector_id);
}
payment_data.mandate_id = Some(payments_api::MandateIds {
@@ -3566,7 +3570,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
mandate_reference_id,
});
- Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data))
+ Ok(ConnectorCallType::PreDetermined(chosen_connector_data))
}
_ => {
let first_choice = connectors
@@ -3581,7 +3585,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
routing_data.merchant_connector_id = first_choice.merchant_connector_id;
}
- Ok(api::ConnectorCallType::Retryable(connectors))
+ Ok(ConnectorCallType::Retryable(connectors))
}
}
}
@@ -3666,7 +3670,7 @@ where
}
}
- let routing_enabled_pms = std::collections::HashSet::from([
+ let routing_enabled_pms = HashSet::from([
enums::PaymentMethodType::GooglePay,
enums::PaymentMethodType::ApplePay,
enums::PaymentMethodType::Klarna,
@@ -3734,7 +3738,7 @@ pub async fn route_connector_v1<F>(
key_store: &domain::MerchantKeyStore,
transaction_data: TransactionData<'_, F>,
routing_data: &mut storage::RoutingData,
- eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
@@ -4025,7 +4029,7 @@ pub async fn payment_external_authentication(
return_url,
req.sdk_information,
req.threeds_method_comp_ind,
- optional_customer.and_then(|customer| customer.email.map(common_utils::pii::Email::from)),
+ optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),
webhook_url,
))
.await?;
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index 1de9cb60ca0..f7fe5b7844f 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -35,7 +35,7 @@ pub fn update_router_data_with_access_token_result<F, Req, Res>(
if should_update_router_data {
match add_access_token_result.access_token_result.as_ref() {
Ok(access_token) => {
- router_data.access_token = access_token.clone();
+ router_data.access_token.clone_from(access_token);
true
}
Err(connector_error) => {
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 6b64dc04044..09b96284544 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -266,7 +266,7 @@ pub async fn authorize_preprocessing_steps<F: Clone>(
Err(types::ErrorResponse::default());
let preprocessing_router_data =
- payments::helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
+ helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
@@ -303,12 +303,11 @@ pub async fn authorize_preprocessing_steps<F: Clone>(
],
);
- let authorize_router_data =
- payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>(
- resp.clone(),
- router_data.request.to_owned(),
- resp.response,
- );
+ let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
+ resp.clone(),
+ router_data.request.to_owned(),
+ resp.response,
+ );
Ok(authorize_router_data)
} else {
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 baf4190395f..667fa3feed0 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -172,7 +172,7 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>(
Err(types::ErrorResponse::default());
let preprocessing_router_data =
- payments::helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
+ helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
@@ -206,15 +206,14 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>(
connector_metadata, ..
}) = &resp.response
{
- router_data_request.connector_meta = connector_metadata.to_owned();
+ connector_metadata.clone_into(&mut router_data_request.connector_meta);
};
- let authorize_router_data =
- payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>(
- resp.clone(),
- router_data_request,
- resp.response,
- );
+ let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
+ resp.clone(),
+ router_data_request,
+ resp.response,
+ );
Ok(authorize_router_data)
} else {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index f17a7075d43..e4c4540cacf 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -636,7 +636,7 @@ pub async fn get_token_for_recurring_mandate(
merchant_connector_id: mandate.merchant_connector_id,
};
- if let Some(diesel_models::enums::PaymentMethod::Card) = payment_method.payment_method {
+ if let Some(enums::PaymentMethod::Card) = payment_method.payment_method {
if state.conf.locker.locker_enabled {
let _ = cards::get_lookup_key_from_locker(
state,
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 87943b4cf2b..8dffd8eaec3 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -59,10 +59,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
helpers::validate_payment_status_against_not_allowed_statuses(
&payment_intent.status,
- &[
- storage_enums::IntentStatus::Failed,
- storage_enums::IntentStatus::Succeeded,
- ],
+ &[IntentStatus::Failed, IntentStatus::Succeeded],
"approve",
)?;
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 3e531280831..32035391fb7 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -112,7 +112,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
- payment_attempt.cancellation_reason = request.cancellation_reason.clone();
+ payment_attempt
+ .cancellation_reason
+ .clone_from(&request.cancellation_reason);
let creds_identifier = request
.merchant_connector_details
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index e770da70747..0d241202208 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -31,7 +31,6 @@ use crate::{
routes::{app::ReqState, AppState},
services,
types::{
- self,
api::{self, PaymentIdTypeExt},
domain,
storage::{
@@ -949,7 +948,7 @@ impl PaymentCreate {
#[allow(clippy::too_many_arguments)]
async fn make_payment_intent(
payment_id: &str,
- merchant_account: &types::domain::MerchantAccount,
+ merchant_account: &domain::MerchantAccount,
money: (api::Amount, enums::Currency),
request: &api::PaymentsRequest,
shipping_address_id: Option<String>,
@@ -971,7 +970,7 @@ impl PaymentCreate {
request.confirm,
);
let client_secret =
- crate::utils::generate_id(consts::ID_LENGTH, format!("{payment_id}_secret").as_str());
+ utils::generate_id(consts::ID_LENGTH, format!("{payment_id}_secret").as_str());
let (amount, currency) = (money.0, Some(money.1));
let order_details = request
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index f4408749fd3..d6e36ca9bfa 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -19,7 +19,6 @@ use crate::{
mandate,
payment_methods::{self, PaymentMethodRetrieve},
payments::{
- self,
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
@@ -722,8 +721,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
Some(multiple_capture_data) => {
let capture_update = storage::CaptureUpdate::ErrorUpdate {
status: match err.status_code {
- 500..=511 => storage::enums::CaptureStatus::Pending,
- _ => storage::enums::CaptureStatus::Failed,
+ 500..=511 => enums::CaptureStatus::Pending,
+ _ => enums::CaptureStatus::Failed,
},
error_code: Some(err.code),
error_message: Some(err.message),
@@ -756,20 +755,20 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
if flow_name == "PSync" {
match err.status_code {
// marking failure for 2xx because this is genuine payment failure
- 200..=299 => storage::enums::AttemptStatus::Failure,
+ 200..=299 => enums::AttemptStatus::Failure,
_ => router_data.status,
}
} else if flow_name == "Capture" {
match err.status_code {
- 500..=511 => storage::enums::AttemptStatus::Pending,
+ 500..=511 => enums::AttemptStatus::Pending,
// don't update the status for 429 error status
429 => router_data.status,
- _ => storage::enums::AttemptStatus::Failure,
+ _ => enums::AttemptStatus::Failure,
}
} else {
match err.status_code {
- 500..=511 => storage::enums::AttemptStatus::Pending,
- _ => storage::enums::AttemptStatus::Failure,
+ 500..=511 => enums::AttemptStatus::Pending,
+ _ => enums::AttemptStatus::Failure,
}
}
}
@@ -891,8 +890,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
};
if router_data.status == enums::AttemptStatus::Charged {
- payment_data.payment_intent.fingerprint_id =
- payment_data.payment_attempt.fingerprint_id.clone();
+ payment_data
+ .payment_intent
+ .fingerprint_id
+ .clone_from(&payment_data.payment_attempt.fingerprint_id);
metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
}
@@ -1070,8 +1071,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
payment_data.authentication = match payment_data.authentication {
Some(authentication) => {
let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate {
- authentication_lifecycle_status:
- storage::enums::AuthenticationLifecycleStatus::Used,
+ authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,
};
let updated_authentication = state
.store
@@ -1154,7 +1154,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
};
if let Some(payment_method) = payment_data.payment_method_info.clone() {
let connector_mandate_details =
- payments::tokenization::update_connector_mandate_details_in_payment_method(
+ tokenization::update_connector_mandate_details_in_payment_method(
payment_method.clone(),
payment_method.payment_method_type,
Some(payment_data.payment_attempt.amount),
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 4c0359c28f0..06ad57346f5 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -289,7 +289,7 @@ async fn get_tracker_for_sync<
)
.await?;
- payment_attempt.encoded_data = request.param.clone();
+ payment_attempt.encoded_data.clone_from(&request.param);
let attempts = match request.expand_attempts {
Some(true) => {
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 0aaa6006052..de83b935ff0 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -727,8 +727,6 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- payment_data.mandate_id = payment_data.mandate_id.clone();
-
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
@@ -832,7 +830,9 @@ impl PaymentUpdate {
payment_intent.business_country = request.business_country;
- payment_intent.business_label = request.business_label.clone();
+ payment_intent
+ .business_label
+ .clone_from(&request.business_label);
request
.description
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 304e6edd62e..6238694b2cc 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -219,9 +219,7 @@ where
};
let pm_card_details = resp.card.as_ref().map(|card| {
- api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
- card.clone(),
- ))
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
});
let pm_data_encrypted =
@@ -257,7 +255,7 @@ where
match &existing_pm_by_locker_id {
Ok(pm) => {
- payment_method_id = pm.payment_method_id.clone()
+ payment_method_id.clone_from(&pm.payment_method_id);
}
Err(_) => {
payment_method_id =
@@ -365,7 +363,8 @@ where
match &existing_pm_by_locker_id {
Ok(pm) => {
- payment_method_id = pm.payment_method_id.clone()
+ payment_method_id
+ .clone_from(&pm.payment_method_id);
}
Err(_) => {
payment_method_id =
@@ -578,7 +577,7 @@ async fn skip_saving_card_in_locker(
.customer_id
.clone()
.get_required_value("customer_id")?;
- let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
+ let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let last4_digits = payment_method_request
.card
@@ -630,7 +629,7 @@ async fn skip_saving_card_in_locker(
Ok((pm_resp, None))
}
None => {
- let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
+ let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_string(),
customer_id: Some(customer_id),
@@ -680,7 +679,7 @@ pub async fn save_in_locker(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed"),
None => {
- let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
+ let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_string(),
customer_id: Some(customer_id),
@@ -746,18 +745,12 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
let pm_token_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
- let mut pm_token_router_data = payments::helpers::router_data_type_conversion::<
- _,
- api::PaymentMethodToken,
- _,
- _,
- _,
- _,
- >(
- router_data.clone(),
- pm_token_request_data,
- pm_token_response_data,
- );
+ let mut pm_token_router_data =
+ helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>(
+ router_data.clone(),
+ pm_token_request_data,
+ pm_token_response_data,
+ );
connector_integration
.execute_pretasks(&mut pm_token_router_data, state)
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 56874e5a9fc..2b7ba070d2c 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1547,8 +1547,8 @@ impl TryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate {
..
} => Ok(Self::ErrorUpdate {
status: match status_code {
- 500..=511 => storage::enums::CaptureStatus::Pending,
- _ => storage::enums::CaptureStatus::Failed,
+ 500..=511 => enums::CaptureStatus::Pending,
+ _ => enums::CaptureStatus::Failed,
},
error_code: Some(code),
error_message: Some(message),
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index e521fac9a80..790cb25c479 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -403,7 +403,9 @@ pub async fn save_payout_data_to_locker(
.await
.flatten()
.map(|card_info| {
- payment_method.payment_method_issuer = card_info.card_issuer.clone();
+ payment_method
+ .payment_method_issuer
+ .clone_from(&card_info.card_issuer);
payment_method.card_network =
card_info.card_network.clone().map(|cn| cn.to_string());
api::payment_methods::PaymentMethodsData::Card(
@@ -641,7 +643,7 @@ pub async fn decide_payout_connector(
request_straight_through: Option<api::routing::StraightThroughAlgorithm>,
routing_data: &mut storage::RoutingData,
payout_data: &mut PayoutData,
- eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
) -> RouterResult<api::ConnectorCallType> {
// 1. For existing attempts, use stored connector
let payout_attempt = &payout_data.payout_attempt;
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index 6bbee9a4cec..a7dcfa864a0 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -114,7 +114,7 @@ pub async fn do_gsm_single_connector_actions(
if let Ordering::Equal = gsm.cmp(&previous_gsm) {
break;
}
- previous_gsm = gsm.clone();
+ previous_gsm.clone_from(&gsm);
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 09ea935ea76..88138d7909f 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -64,7 +64,7 @@ pub async fn create_link_token(
let redis_conn = db
.get_redis_conn()
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let pm_auth_key = format!("pm_auth_{}", payload.payment_id);
@@ -75,7 +75,7 @@ pub async fn create_link_token(
"Vec<PaymentMethodAuthConnectorChoice>",
)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get payment method auth choices from redis")?;
let selected_config = pm_auth_configs
@@ -132,7 +132,7 @@ pub async fn create_link_token(
&key_store,
)
.await
- .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_account.merchant_id.clone(),
})?;
@@ -145,7 +145,7 @@ pub async fn create_link_token(
request: pm_auth_types::LinkTokenRequest {
client_name: "HyperSwitch".to_string(),
country_codes: Some(vec![billing_country.ok_or(
- errors::ApiErrorResponse::MissingRequiredField {
+ ApiErrorResponse::MissingRequiredField {
field_name: "billing_country",
},
)?]),
@@ -216,8 +216,7 @@ pub async fn exchange_token_core(
let connector_name = config.connector_name.as_str();
- let connector =
- pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
+ let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
let merchant_connector_account = state
.store
@@ -227,7 +226,7 @@ pub async fn exchange_token_core(
&key_store,
)
.await
- .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_account.merchant_id.clone(),
})?;
@@ -405,9 +404,7 @@ async fn store_bank_details_in_payment_methods(
connector_details: vec![payment_methods::BankAccountConnectorDetails {
connector: connector_name.to_string(),
mca_id: mca_id.clone(),
- access_token: payment_methods::BankAccountAccessCreds::AccessToken(
- access_token.clone(),
- ),
+ access_token: BankAccountAccessCreds::AccessToken(access_token.clone()),
account_id: creds.account_id,
}],
};
@@ -612,7 +609,7 @@ async fn get_selected_config_from_redis(
) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> {
let redis_conn = db
.get_redis_conn()
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let pm_auth_key = format!("pm_auth_{}", payload.payment_id);
@@ -623,7 +620,7 @@ async fn get_selected_config_from_redis(
"Vec<PaymentMethodAuthConnectorChoice>",
)
.await
- .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ .change_context(ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector name not found".to_string(),
})
.attach_printable("Failed to get payment method auth choices from redis")?;
@@ -651,14 +648,14 @@ pub async fn retrieve_payment_method_from_auth_service(
) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> {
let db = state.store.as_ref();
- let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(
+ let connector = PaymentAuthConnectorData::get_connector_by_name(
auth_token.connector_details.connector.as_str(),
)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store)
.await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+ .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
@@ -667,7 +664,7 @@ pub async fn retrieve_payment_method_from_auth_service(
key_store,
)
.await
- .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: auth_token.connector_details.mca_id.clone(),
})
.attach_printable(
@@ -697,7 +694,7 @@ pub async fn retrieve_payment_method_from_auth_service(
acc.payment_method_type == auth_token.payment_method_type
&& acc.payment_method == auth_token.payment_method
})
- .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Bank account details not found")?;
let mut bank_type = None;
@@ -720,7 +717,7 @@ pub async fn retrieve_payment_method_from_auth_service(
let name = address
.as_ref()
.and_then(|addr| addr.first_name.clone().map(|name| name.into_inner()))
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ .ok_or(ApiErrorResponse::GenericNotFoundError {
message: "billing_first_name not found".to_string(),
})
.attach_printable("billing_first_name not found")?;
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index c3512c32f42..ee1693b0c9d 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -8,15 +8,15 @@ use masking::ExposeInterface;
#[cfg(feature = "email")]
use router_env::logger;
+#[cfg(feature = "email")]
+use crate::services::email::types as email_types;
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::{app::ReqState, AppState},
services::{authentication::UserFromToken, ApplicationResponse},
- types::domain::{user::dashboard_metadata as types, MerchantKeyStore},
+ types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore},
utils::user::dashboard_metadata as utils,
};
-#[cfg(feature = "email")]
-use crate::{services::email::types as email_types, types::domain};
pub async fn set_metadata(
state: AppState,
@@ -709,7 +709,7 @@ pub async fn get_merchant_connector_account_by_name(
merchant_id: &str,
connector_name: &str,
key_store: &MerchantKeyStore,
-) -> UserResult<Option<crate::types::domain::MerchantConnectorAccount>> {
+) -> UserResult<Option<domain::MerchantConnectorAccount>> {
state
.store
.find_merchant_connector_account_by_merchant_id_connector_name(
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 3923663f5d1..ac546ef5e49 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -564,7 +564,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
dispute_id: dispute.dispute_id.clone(),
connector_dispute_id: dispute.connector_dispute_id.clone(),
},
- response: Err(types::ErrorResponse::default()),
+ response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
@@ -654,7 +654,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
connector_meta_data: merchant_connector_account.get_metadata(),
amount_captured: payment_intent.amount_captured,
request: submit_evidence_request_data,
- response: Err(types::ErrorResponse::default()),
+ response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
@@ -752,7 +752,7 @@ pub async fn construct_upload_file_router_data<'a>(
file_type: create_file_request.file_type.clone(),
file_size: create_file_request.file_size,
},
- response: Err(types::ErrorResponse::default()),
+ response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
@@ -936,7 +936,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing provider file id")?,
},
- response: Err(types::ErrorResponse::default()),
+ response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
@@ -1225,9 +1225,7 @@ pub fn get_incremental_authorization_allowed_value(
incremental_authorization_allowed: Option<bool>,
request_incremental_authorization: Option<RequestIncrementalAuthorization>,
) -> Option<bool> {
- if request_incremental_authorization
- == Some(common_enums::RequestIncrementalAuthorization::False)
- {
+ if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) {
Some(false)
} else {
incremental_authorization_allowed
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs
index 8782126b0b6..fe3d752497a 100644
--- a/crates/router/src/core/verification.rs
+++ b/crates/router/src/core/verification.rs
@@ -89,7 +89,7 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
merchant_id: String,
merchant_connector_id: String,
) -> CustomResult<
- services::ApplicationResponse<api_models::verifications::ApplepayVerifiedDomainsResponse>,
+ services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,
api_error_response::ApiErrorResponse,
> {
let db = state.store.as_ref();
@@ -110,6 +110,6 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
.unwrap_or_default();
Ok(services::api::ApplicationResponse::Json(
- api_models::verifications::ApplepayVerifiedDomainsResponse { verified_domains },
+ verifications::ApplepayVerifiedDomainsResponse { verified_domains },
))
}
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 6647549e399..3c04fdb7e49 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -74,7 +74,7 @@ pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>(
payments::CallConnectorAction::Trigger
};
let payments_response = match webhook_details.object_reference_id {
- api_models::webhooks::ObjectReferenceId::PaymentId(id) => {
+ webhooks::ObjectReferenceId::PaymentId(id) => {
let payment_id = get_payment_id(
state.store.as_ref(),
&id,
@@ -84,7 +84,7 @@ pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>(
.await?;
let lock_action = api_locking::LockAction::Hold {
- input: super::api_locking::LockingInput {
+ input: api_locking::LockingInput {
unique_locking_key: payment_id,
api_identifier: lock_utils::ApiIdentifier::Payments,
override_lock_retries: None,
@@ -213,13 +213,13 @@ pub async fn refunds_incoming_webhook_flow(
webhook_details: api::IncomingWebhookDetails,
connector_name: &str,
source_verified: bool,
- event_type: api_models::webhooks::IncomingWebhookEvent,
+ event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let db = &*state.store;
//find refund by connector refund id
let refund = match webhook_details.object_reference_id {
- api_models::webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
- api_models::webhooks::RefundIdType::RefundId(id) => db
+ webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
+ webhooks::RefundIdType::RefundId(id) => db
.find_refund_by_merchant_id_refund_id(
&merchant_account.merchant_id,
&id,
@@ -228,7 +228,7 @@ pub async fn refunds_incoming_webhook_flow(
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the refund")?,
- api_models::webhooks::RefundIdType::ConnectorRefundId(id) => db
+ webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
&merchant_account.merchant_id,
&id,
@@ -305,7 +305,7 @@ pub async fn refunds_incoming_webhook_flow(
pub async fn get_payment_attempt_from_object_reference_id(
state: &AppState,
- object_reference_id: api_models::webhooks::ObjectReferenceId,
+ object_reference_id: webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
@@ -349,7 +349,7 @@ pub async fn get_or_update_dispute_object(
dispute_details: api::disputes::DisputePayload,
merchant_id: &str,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
- event_type: api_models::webhooks::IncomingWebhookEvent,
+ event_type: webhooks::IncomingWebhookEvent,
business_profile: &diesel_models::business_profile::BusinessProfile,
connector_name: &str,
) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> {
@@ -425,7 +425,7 @@ pub async fn external_authentication_incoming_webhook_flow<Ctx: PaymentMethodRet
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
source_verified: bool,
- event_type: api_models::webhooks::IncomingWebhookEvent,
+ event_type: webhooks::IncomingWebhookEvent,
request_details: &api::IncomingWebhookRequestDetails<'_>,
connector: &(dyn api::Connector + Sync),
object_ref_id: api::ObjectReferenceId,
@@ -601,7 +601,7 @@ pub async fn mandates_incoming_webhook_flow(
key_store: domain::MerchantKeyStore,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
- event_type: api_models::webhooks::IncomingWebhookEvent,
+ event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
if source_verified {
let db = &*state.store;
@@ -691,7 +691,7 @@ pub async fn disputes_incoming_webhook_flow(
source_verified: bool,
connector: &(dyn api::Connector + Sync),
request_details: &api::IncomingWebhookRequestDetails<'_>,
- event_type: api_models::webhooks::IncomingWebhookEvent,
+ event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]);
if source_verified {
@@ -1612,7 +1612,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr
let is_webhook_event_supported = !matches!(
event_type,
- api_models::webhooks::IncomingWebhookEvent::EventNotSupported
+ webhooks::IncomingWebhookEvent::EventNotSupported
);
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
@@ -2102,7 +2102,7 @@ pub(crate) fn get_outgoing_webhook_request(
>(
outgoing_webhook, payment_response_hash_key
),
- _ => get_outgoing_webhook_request_inner::<api_models::webhooks::OutgoingWebhook>(
+ _ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
payment_response_hash_key,
),
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 3bf8c7c7f21..ad1aafd3125 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -124,8 +124,8 @@ pub async fn construct_webhook_router_data<'a>(
#[inline]
pub(crate) fn get_idempotent_event_id(
primary_object_id: &str,
- event_type: crate::types::storage::enums::EventType,
- delivery_attempt: crate::types::storage::enums::WebhookDeliveryAttempt,
+ event_type: types::storage::enums::EventType,
+ delivery_attempt: types::storage::enums::WebhookDeliveryAttempt,
) -> String {
use crate::types::storage::enums::WebhookDeliveryAttempt;
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 9b222486d18..ca9432fcba9 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -190,7 +190,7 @@ where
let bytes = db.get_key(key).await?;
bytes
.parse_struct(type_name)
- .change_context(redis_interface::errors::RedisError::JsonDeserializationFailed)
+ .change_context(RedisError::JsonDeserializationFailed)
}
dyn_clone::clone_trait_object!(StorageInterface);
diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs
index 7b5ade8c965..5e7c9bd0b20 100644
--- a/crates/router/src/db/business_profile.rs
+++ b/crates/router/src/db/business_profile.rs
@@ -6,7 +6,7 @@ use crate::{
connection,
core::errors::{self, CustomResult},
db::MockDb,
- types::storage::{self, business_profile},
+ types::storage::business_profile,
};
#[async_trait::async_trait]
@@ -65,7 +65,7 @@ impl BusinessProfileInterface for Store {
profile_id: &str,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::business_profile::BusinessProfile::find_by_profile_id(&conn, profile_id)
+ business_profile::BusinessProfile::find_by_profile_id(&conn, profile_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
@@ -77,7 +77,7 @@ impl BusinessProfileInterface for Store {
merchant_id: &str,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::business_profile::BusinessProfile::find_by_profile_name_merchant_id(
+ business_profile::BusinessProfile::find_by_profile_name_merchant_id(
&conn,
profile_name,
merchant_id,
@@ -93,7 +93,7 @@ impl BusinessProfileInterface for Store {
business_profile_update: business_profile::BusinessProfileUpdate,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- storage::business_profile::BusinessProfile::update_by_profile_id(
+ business_profile::BusinessProfile::update_by_profile_id(
current_state,
&conn,
business_profile_update,
@@ -109,7 +109,7 @@ impl BusinessProfileInterface for Store {
merchant_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- storage::business_profile::BusinessProfile::delete_by_profile_id_merchant_id(
+ business_profile::BusinessProfile::delete_by_profile_id_merchant_id(
&conn,
profile_id,
merchant_id,
@@ -124,12 +124,9 @@ impl BusinessProfileInterface for Store {
merchant_id: &str,
) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::business_profile::BusinessProfile::list_business_profile_by_merchant_id(
- &conn,
- merchant_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
+ business_profile::BusinessProfile::list_business_profile_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
}
}
diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs
index 7f2462b3fc8..d9db13dde80 100644
--- a/crates/router/src/db/cache.rs
+++ b/crates/router/src/db/cache.rs
@@ -43,7 +43,7 @@ where
};
match redis_val {
Err(err) => match err.current_context() {
- errors::RedisError::NotFound | errors::RedisError::JsonDeserializationFailed => {
+ RedisError::NotFound | RedisError::JsonDeserializationFailed => {
get_data_set_redis().await
}
_ => Err(err
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 0fe5f3d7666..097ad9beab9 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -444,7 +444,7 @@ mod tests {
#[tokio::test]
async fn test_find_by_merchant_id_payment_id_connector_dispute_id() {
#[allow(clippy::expect_used)]
- let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ let mockdb = MockDb::new(&RedisSettings::default())
.await
.expect("Failed to create Mock store");
@@ -487,7 +487,7 @@ mod tests {
#[tokio::test]
async fn test_find_dispute_by_merchant_id_dispute_id() {
#[allow(clippy::expect_used)]
- let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ let mockdb = MockDb::new(&RedisSettings::default())
.await
.expect("Failed to create Mock store");
@@ -524,7 +524,7 @@ mod tests {
#[tokio::test]
async fn test_find_disputes_by_merchant_id() {
#[allow(clippy::expect_used)]
- let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ let mockdb = MockDb::new(&RedisSettings::default())
.await
.expect("Failed to create Mock store");
@@ -578,7 +578,7 @@ mod tests {
#[tokio::test]
async fn test_find_disputes_by_merchant_id_payment_id() {
#[allow(clippy::expect_used)]
- let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ let mockdb = MockDb::new(&RedisSettings::default())
.await
.expect("Failed to create Mock store");
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index e31a2663354..fff82334be0 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -377,8 +377,8 @@ impl UserRoleInterface for MockDb {
status,
modified_by,
} => {
- user_role.status = status.to_owned();
- user_role.last_modified_by = modified_by.to_owned();
+ status.clone_into(&mut user_role.status);
+ modified_by.clone_into(&mut user_role.last_modified_by);
}
}
updated_user_roles.push(user_role.to_owned());
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index fdabd07fa01..d11e5cf997a 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -188,7 +188,7 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio
errors::ApplicationError::ApiClientError(error.current_context().clone())
})?,
);
- let state = Box::pin(routes::AppState::new(conf, tx, api_client)).await;
+ let state = Box::pin(AppState::new(conf, tx, api_client)).await;
let request_body_limit = server.request_body_limit;
let server = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit))
.bind((server.host.as_str(), server.port))?
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 55959589152..f1170f0f0bb 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -131,7 +131,7 @@ pub async fn api_key_update(
let (merchant_id, key_id) = path.into_inner();
let mut payload = json_payload.into_inner();
payload.key_id = key_id;
- payload.merchant_id = merchant_id.clone();
+ payload.merchant_id.clone_from(&merchant_id);
api::server_wrap(
flow,
diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs
index 029c1c61f24..ef53ad83f2c 100644
--- a/crates/router/src/routes/metrics/request.rs
+++ b/crates/router/src/routes/metrics/request.rs
@@ -24,7 +24,7 @@ where
#[inline]
pub async fn record_operation_time<F, R>(
future: F,
- metric: &once_cell::sync::Lazy<router_env::opentelemetry::metrics::Histogram<f64>>,
+ metric: &once_cell::sync::Lazy<opentelemetry::metrics::Histogram<f64>>,
key_value: &[opentelemetry::KeyValue],
) -> R
where
@@ -35,11 +35,11 @@ where
result
}
-pub fn add_attributes<T: Into<router_env::opentelemetry::Value>>(
+pub fn add_attributes<T: Into<opentelemetry::Value>>(
key: &'static str,
value: T,
-) -> router_env::opentelemetry::KeyValue {
- router_env::opentelemetry::KeyValue::new(key, value)
+) -> opentelemetry::KeyValue {
+ opentelemetry::KeyValue::new(key, value)
}
pub fn status_code_metrics(status_code: i64, flow: String, merchant_id: String) {
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index c9e1cf14ce3..70112e27037 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -131,7 +131,7 @@ pub async fn payments_create(
req_state,
auth.merchant_account,
auth.key_store,
- payment_types::HeaderPayload::default(),
+ HeaderPayload::default(),
req,
api::AuthFlow::Merchant,
)
@@ -420,7 +420,7 @@ pub async fn payments_update(
req_state,
auth.merchant_account,
auth.key_store,
- payment_types::HeaderPayload::default(),
+ HeaderPayload::default(),
req,
auth_flow,
)
@@ -471,7 +471,7 @@ pub async fn payments_confirm(
tracing::Span::current().record("payment_id", &payment_id);
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true);
- let header_payload = match payment_types::HeaderPayload::foreign_try_from(req.headers()) {
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
@@ -1019,7 +1019,7 @@ pub async fn payments_approve(
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
- payment_types::HeaderPayload::default(),
+ HeaderPayload::default(),
)
},
match env::which() {
@@ -1081,7 +1081,7 @@ pub async fn payments_reject(
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
- payment_types::HeaderPayload::default(),
+ HeaderPayload::default(),
)
},
match env::which() {
@@ -1107,7 +1107,7 @@ async fn authorize_verify_select<Op, Ctx>(
header_payload: HeaderPayload,
req: api_models::payments::PaymentsRequest,
auth_flow: api::AuthFlow,
-) -> app::core::errors::RouterResponse<api_models::payments::PaymentsResponse>
+) -> errors::RouterResponse<api_models::payments::PaymentsResponse>
where
Ctx: PaymentMethodRetrieve,
Op: Sync
@@ -1530,8 +1530,10 @@ impl GetLockingInput for payment_types::PaymentsCaptureRequest {
}
}
+#[cfg(feature = "oltp")]
struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest);
+#[cfg(feature = "oltp")]
impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
@@ -1548,8 +1550,10 @@ impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> {
}
}
+#[cfg(feature = "oltp")]
struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest);
+#[cfg(feature = "oltp")]
impl<'a> GetLockingInput for FPaymentsRejectRequest<'a> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs
index 7845f52c924..fc0794ff9e0 100644
--- a/crates/router/src/routes/recon.rs
+++ b/crates/router/src/routes/recon.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::recon as recon_api;
-use common_enums::ReconStatus;
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::Flow;
@@ -195,7 +194,7 @@ pub async fn recon_merchant_account_update(
subject: "Approval of Recon Request - Access Granted to Recon Dashboard",
};
- if req.recon_status == ReconStatus::Active {
+ if req.recon_status == enums::ReconStatus::Active {
let _is_email_sent = state
.email_client
.compose_and_send_email(
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index ede6edbceb8..641ee5648f8 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -159,9 +159,10 @@ pub async fn set_dashboard_metadata(
let flow = Flow::SetDashboardMetadata;
let mut payload = json_payload.into_inner();
- if let Err(e) = common_utils::errors::ReportSwitchExt::<(), ApiErrorResponse>::switch(
- set_ip_address_if_required(&mut payload, req.headers()),
- ) {
+ if let Err(e) = ReportSwitchExt::<(), ApiErrorResponse>::switch(set_ip_address_if_required(
+ &mut payload,
+ req.headers(),
+ )) {
return api::log_and_return_error_response(e);
}
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index 073b1c57000..cdf680548a1 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -43,19 +43,3 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
))
.await
}
-
-#[derive(Debug)]
-struct WebhookBytes(web::Bytes);
-
-impl serde::Serialize for WebhookBytes {
- fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- let payload: serde_json::Value = serde_json::from_slice(&self.0).unwrap_or_default();
- payload.serialize(serializer)
- }
-}
-
-impl common_utils::events::ApiEventMetric for WebhookBytes {
- fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
- Some(common_utils::events::ApiEventsType::Miscellaneous)
- }
-}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 30c3ce164e2..cfe4fea11bb 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -273,7 +273,7 @@ pub enum CaptureSyncMethod {
pub async fn execute_connector_processing_step<
'b,
'a,
- T: 'static,
+ T,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
@@ -284,7 +284,7 @@ pub async fn execute_connector_processing_step<
connector_request: Option<Request>,
) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
where
- T: Clone + Debug,
+ T: Clone + Debug + 'static,
// BoxedConnectorIntegration<T, Req, Resp>: 'b,
{
// If needed add an error stack as follows
@@ -651,7 +651,7 @@ pub async fn send_request(
}
.add_headers(headers)
.timeout(Duration::from_secs(
- option_timeout_secs.unwrap_or(crate::consts::REQUEST_TIME_OUT),
+ option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT),
))
};
@@ -920,7 +920,7 @@ pub enum RedirectForm {
impl From<(url::Url, Method)> for RedirectForm {
fn from((mut redirect_url, method): (url::Url, Method)) -> Self {
- let form_fields = std::collections::HashMap::from_iter(
+ let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
@@ -1127,10 +1127,7 @@ where
if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) {
acc.insert(key.clone(), value.clone());
} else {
- acc.insert(
- key.clone(),
- http::header::HeaderValue::from_static("**MASKED**"),
- );
+ acc.insert(key.clone(), HeaderValue::from_static("**MASKED**"));
}
acc
});
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index 09b4d25d0b6..ae45a2a7fce 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -27,7 +27,7 @@ fn get_client_builder(
) -> CustomResult<reqwest::ClientBuilder, ApiClientError> {
let mut client_builder = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
- .pool_idle_timeout(std::time::Duration::from_secs(
+ .pool_idle_timeout(Duration::from_secs(
proxy_config
.idle_pool_connection_timeout
.unwrap_or_default(),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 5f15474115d..9aac92acd2a 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -876,13 +876,13 @@ impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {
}
}
-impl ClientSecretFetch for api_models::payments::PaymentsRetrieveRequest {
+impl ClientSecretFetch for payments::PaymentsRetrieveRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
-impl ClientSecretFetch for api_models::payments::RetrievePaymentLinkRequest {
+impl ClientSecretFetch for payments::RetrievePaymentLinkRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rs
index 91b752aaf13..a54ba881995 100644
--- a/crates/router/src/services/pm_auth.rs
+++ b/crates/router/src/services/pm_auth.rs
@@ -11,22 +11,16 @@ use crate::{
services::{self},
};
-pub async fn execute_connector_processing_step<
- 'b,
- 'a,
- T: 'static,
- Req: Clone + 'static,
- Resp: Clone + 'static,
->(
+pub async fn execute_connector_processing_step<'b, 'a, T, Req, Resp>(
state: &'b AppState,
connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>,
req: &'b PaymentAuthRouterData<T, Req, Resp>,
connector: &pm_auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError>
where
- T: Clone,
- Req: Clone,
- Resp: Clone,
+ T: Clone + 'static,
+ Req: Clone + 'static,
+ Resp: Clone + 'static,
{
let mut router_data = req.clone();
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index 6f08a7fd7e4..e0ef95bcb0d 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -3,7 +3,7 @@ pub use api_models::customers::{CustomerDeleteResponse, CustomerId, CustomerRequ
use serde::Serialize;
use super::payments;
-use crate::{core::errors::RouterResult, newtype, types::domain};
+use crate::{newtype, types::domain};
newtype!(
pub CustomerResponse = customers::CustomerResponse,
@@ -16,10 +16,6 @@ impl common_utils::events::ApiEventMetric for CustomerResponse {
}
}
-pub(crate) trait CustomerRequestExt: Sized {
- fn validate(self) -> RouterResult<Self>;
-}
-
impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
fn from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self {
customers::CustomerResponse {
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index e36c68c27d5..9f68cac98c9 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -21,20 +21,6 @@ use crate::{
types::{self, api as api_types},
};
-pub(crate) trait PaymentsRequestExt {
- fn is_mandate(&self) -> Option<MandateTransactionType>;
-}
-
-impl PaymentsRequestExt for PaymentsRequest {
- fn is_mandate(&self) -> Option<MandateTransactionType> {
- match (&self.mandate_data, &self.mandate_id) {
- (None, None) => None,
- (_, Some(_)) => Some(MandateTransactionType::RecurringMandateTransaction),
- (Some(_), _) => Some(MandateTransactionType::NewMandateTransaction),
- }
- }
-}
-
impl super::Router for PaymentsRequest {}
// Core related api layer.
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 39891a7075d..af7cb9160b2 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -14,7 +14,7 @@ use crate::{
#[derive(Clone, Debug)]
pub struct VerifyConnectorData {
- pub connector: &'static (dyn types::api::Connector + Sync),
+ pub connector: &'static (dyn api::Connector + Sync),
pub connector_auth: types::ConnectorAuthType,
pub card_details: domain::Card,
}
@@ -155,11 +155,11 @@ pub trait VerifyConnector {
}
async fn handle_payment_error_response<F, R1, R2>(
- connector: &(dyn types::api::Connector + Sync),
+ connector: &(dyn api::Connector + Sync),
error_response: types::Response,
) -> errors::RouterResponse<()>
where
- dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
+ dyn api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
.get_error_response(error_response, None)
@@ -171,11 +171,11 @@ pub trait VerifyConnector {
}
async fn handle_access_token_error_response<F, R1, R2>(
- connector: &(dyn types::api::Connector + Sync),
+ connector: &(dyn api::Connector + Sync),
error_response: types::Response,
) -> errors::RouterResult<Option<types::AccessToken>>
where
- dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
+ dyn api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
.get_error_response(error_response, None)
diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs
index de95251d9d4..139cd105779 100644
--- a/crates/router/src/types/domain/customer.rs
+++ b/crates/router/src/types/domain/customer.rs
@@ -148,14 +148,14 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
},
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
- modified_at: Some(common_utils::date_time::now()),
+ modified_at: Some(date_time::now()),
..Default::default()
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
- modified_at: Some(common_utils::date_time::now()),
+ modified_at: Some(date_time::now()),
..Default::default()
},
}
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index c84abbefc38..0e7f5b081c3 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -195,7 +195,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
metadata,
frm_configs: None,
frm_config: frm_configs,
- modified_at: Some(common_utils::date_time::now()),
+ modified_at: Some(date_time::now()),
connector_webhook_details,
applepay_verified_domains,
pm_auth_config,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index ef12e32d57c..ce11251b83e 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -176,20 +176,18 @@ impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStat
}
}
-impl ForeignFrom<api_models::payments::MandateType> for storage_enums::MandateDataType {
- fn foreign_from(from: api_models::payments::MandateType) -> Self {
+impl ForeignFrom<payments::MandateType> for storage_enums::MandateDataType {
+ fn foreign_from(from: payments::MandateType) -> Self {
match from {
- api_models::payments::MandateType::SingleUse(inner) => {
- Self::SingleUse(inner.foreign_into())
- }
- api_models::payments::MandateType::MultiUse(inner) => {
+ payments::MandateType::SingleUse(inner) => Self::SingleUse(inner.foreign_into()),
+ payments::MandateType::MultiUse(inner) => {
Self::MultiUse(inner.map(ForeignInto::foreign_into))
}
}
}
}
-impl ForeignFrom<storage_enums::MandateDataType> for api_models::payments::MandateType {
+impl ForeignFrom<storage_enums::MandateDataType> for payments::MandateType {
fn foreign_from(from: storage_enums::MandateDataType) -> Self {
match from {
storage_enums::MandateDataType::SingleUse(inner) => {
@@ -302,7 +300,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
}
}
-impl ForeignFrom<storage_enums::MandateAmountData> for api_models::payments::MandateAmountData {
+impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData {
fn foreign_from(from: storage_enums::MandateAmountData) -> Self {
Self {
amount: from.amount,
@@ -315,18 +313,16 @@ impl ForeignFrom<storage_enums::MandateAmountData> for api_models::payments::Man
}
// TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information
-impl ForeignFrom<api_models::payments::MandateData>
- for hyperswitch_domain_models::mandates::MandateData
-{
- fn foreign_from(d: api_models::payments::MandateData) -> Self {
+impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData {
+ fn foreign_from(d: payments::MandateData) -> Self {
Self {
customer_acceptance: d.customer_acceptance.map(|d| {
hyperswitch_domain_models::mandates::CustomerAcceptance {
acceptance_type: match d.acceptance_type {
- api_models::payments::AcceptanceType::Online => {
+ payments::AcceptanceType::Online => {
hyperswitch_domain_models::mandates::AcceptanceType::Online
}
- api_models::payments::AcceptanceType::Offline => {
+ payments::AcceptanceType::Offline => {
hyperswitch_domain_models::mandates::AcceptanceType::Offline
}
},
@@ -340,7 +336,7 @@ impl ForeignFrom<api_models::payments::MandateData>
}
}),
mandate_type: d.mandate_type.map(|d| match d {
- api_models::payments::MandateType::MultiUse(Some(i)) => {
+ payments::MandateType::MultiUse(Some(i)) => {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(
hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
@@ -351,7 +347,7 @@ impl ForeignFrom<api_models::payments::MandateData>
},
))
}
- api_models::payments::MandateType::SingleUse(i) => {
+ payments::MandateType::SingleUse(i) => {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(
hyperswitch_domain_models::mandates::MandateAmountData {
amount: i.amount,
@@ -362,7 +358,7 @@ impl ForeignFrom<api_models::payments::MandateData>
},
)
}
- api_models::payments::MandateType::MultiUse(None) => {
+ payments::MandateType::MultiUse(None) => {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None)
}
}),
@@ -371,8 +367,8 @@ impl ForeignFrom<api_models::payments::MandateData>
}
}
-impl ForeignFrom<api_models::payments::MandateAmountData> for storage_enums::MandateAmountData {
- fn foreign_from(from: api_models::payments::MandateAmountData) -> Self {
+impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData {
+ fn foreign_from(from: payments::MandateAmountData) -> Self {
Self {
amount: from.amount,
currency: from.currency,
@@ -503,26 +499,27 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
}
}
-impl ForeignTryFrom<api_models::payments::PaymentMethodData> for api_enums::PaymentMethod {
+impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(
- payment_method_data: api_models::payments::PaymentMethodData,
+ payment_method_data: payments::PaymentMethodData,
) -> Result<Self, Self::Error> {
match payment_method_data {
- api_models::payments::PaymentMethodData::Card(..)
- | api_models::payments::PaymentMethodData::CardToken(..) => 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::CardRedirect(..) => Ok(Self::CardRedirect),
- api_models::payments::PaymentMethodData::MandatePayment => {
+ payments::PaymentMethodData::Card(..) | payments::PaymentMethodData::CardToken(..) => {
+ Ok(Self::Card)
+ }
+ payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet),
+ payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater),
+ payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect),
+ payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit),
+ payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer),
+ payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto),
+ payments::PaymentMethodData::Reward => Ok(Self::Reward),
+ payments::PaymentMethodData::Upi(..) => Ok(Self::Upi),
+ payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher),
+ payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard),
+ payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect),
+ payments::PaymentMethodData::MandatePayment => {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("Mandate payments cannot have payment_method_data field".to_string()),
})
@@ -902,7 +899,7 @@ impl TryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantCo
}
}
-impl ForeignFrom<storage::PaymentAttempt> for api_models::payments::PaymentAttemptResponse {
+impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self {
Self {
attempt_id: payment_attempt.attempt_id,
@@ -929,7 +926,7 @@ impl ForeignFrom<storage::PaymentAttempt> for api_models::payments::PaymentAttem
}
}
-impl ForeignFrom<storage::Capture> for api_models::payments::CaptureResponse {
+impl ForeignFrom<storage::Capture> for payments::CaptureResponse {
fn foreign_from(capture: storage::Capture) -> Self {
Self {
capture_id: capture.capture_id,
@@ -1003,7 +1000,7 @@ impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod {
}
}
-impl ForeignTryFrom<&HeaderMap> for api_models::payments::HeaderPayload {
+impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> {
let payment_confirm_source: Option<api_enums::PaymentSource> =
@@ -1047,7 +1044,7 @@ impl
Option<&domain::Address>,
Option<&domain::Address>,
Option<&domain::Customer>,
- )> for api_models::payments::PaymentsRequest
+ )> for payments::PaymentsRequest
{
fn foreign_from(
value: (
@@ -1072,17 +1069,11 @@ impl
}
}
-impl
- ForeignFrom<(
- storage::PaymentLink,
- api_models::payments::PaymentLinkStatus,
- )> for api_models::payments::RetrievePaymentLinkResponse
+impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)>
+ for payments::RetrievePaymentLinkResponse
{
fn foreign_from(
- (payment_link_config, status): (
- storage::PaymentLink,
- api_models::payments::PaymentLinkStatus,
- ),
+ (payment_link_config, status): (storage::PaymentLink, payments::PaymentLinkStatus),
) -> Self {
Self {
payment_link_id: payment_link_config.payment_link_id,
@@ -1171,7 +1162,7 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse {
}
}
-impl ForeignFrom<&domain::Customer> for api_models::payments::CustomerDetails {
+impl ForeignFrom<&domain::Customer> for payments::CustomerDetails {
fn foreign_from(customer: &domain::Customer) -> Self {
Self {
id: customer.customer_id.clone(),
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 341c560e4d2..51854978b9e 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -99,7 +99,7 @@ pub mod error_parser {
}
pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error {
- actix_web::error::Error::from(CustomJsonError { err })
+ Error::from(CustomJsonError { err })
}
}
@@ -565,14 +565,14 @@ pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) {
pub trait CustomerAddress {
async fn get_address_update(
&self,
- address_details: api_models::payments::AddressDetails,
+ address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>;
async fn get_domain_address(
&self,
- address_details: api_models::payments::AddressDetails,
+ address_details: payments::AddressDetails,
merchant_id: &str,
customer_id: &str,
key: &[u8],
@@ -584,7 +584,7 @@ pub trait CustomerAddress {
impl CustomerAddress for api_models::customers::CustomerRequest {
async fn get_address_update(
&self,
- address_details: api_models::payments::AddressDetails,
+ address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> {
@@ -640,7 +640,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
async fn get_domain_address(
&self,
- address_details: api_models::payments::AddressDetails,
+ address_details: payments::AddressDetails,
merchant_id: &str,
customer_id: &str,
key: &[u8],
diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs
index 912f8fce94c..5cf68635c4e 100644
--- a/crates/router/src/utils/currency.rs
+++ b/crates/router/src/utils/currency.rs
@@ -525,10 +525,10 @@ pub async fn convert_currency(
.await
.change_context(ForexCacheError::ApiError)?;
- let to_currency = api_models::enums::Currency::from_str(to_currency.as_str())
+ let to_currency = enums::Currency::from_str(to_currency.as_str())
.change_context(ForexCacheError::CurrencyNotAcceptable)?;
- let from_currency = api_models::enums::Currency::from_str(from_currency.as_str())
+ let from_currency = enums::Currency::from_str(from_currency.as_str())
.change_context(ForexCacheError::CurrencyNotAcceptable)?;
let converted_amount =
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index bde0fb72bd3..33e9aa6769c 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -11,7 +11,7 @@ use crate::{
routes::AppState,
services::{
authentication::{AuthToken, UserFromToken},
- authorization::roles::{self, RoleInfo},
+ authorization::roles::RoleInfo,
},
types::domain::{self, MerchantAccount, UserFromStorage},
};
@@ -64,7 +64,7 @@ impl UserFromToken {
}
pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> {
- roles::RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
+ RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
.await
.change_context(UserErrors::InternalServerError)
}
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 710d90a4ea3..2e5e8748f48 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -46,7 +46,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
@@ -263,7 +263,7 @@ async fn payments_create_failure() {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
});
let response = services::api::execute_connector_processing_step(
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 468834ca495..d19fff29003 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -151,7 +151,7 @@ impl AdyenTest {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs
index 95b07162ac3..2ef61099ca7 100644
--- a/crates/router/tests/connectors/airwallex.rs
+++ b/crates/router/tests/connectors/airwallex.rs
@@ -70,7 +70,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4035501000000008").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
@@ -80,7 +80,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
router_return_url: Some("https://google.com".to_string()),
@@ -143,7 +143,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -272,7 +272,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -370,7 +370,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
@@ -393,7 +393,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -416,7 +416,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -439,7 +439,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index 2b9a79b0b7b..4c724f368d7 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -55,9 +55,7 @@ async fn should_only_authorize_payment() {
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 300,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -72,7 +70,7 @@ async fn should_only_authorize_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -92,9 +90,7 @@ async fn should_capture_authorized_payment() {
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 301,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -109,9 +105,7 @@ async fn should_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.clone(),
- ),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -137,7 +131,7 @@ async fn should_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -156,9 +150,7 @@ async fn should_partially_capture_authorized_payment() {
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 302,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -173,9 +165,7 @@ async fn should_partially_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.clone(),
- ),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -201,7 +191,7 @@ async fn should_partially_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -220,9 +210,7 @@ async fn should_sync_authorized_payment() {
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 303,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -237,7 +225,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -256,9 +244,7 @@ async fn should_void_authorized_payment() {
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 304,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -273,9 +259,7 @@ async fn should_void_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.clone(),
- ),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -307,9 +291,7 @@ async fn should_make_payment() {
.make_payment(
Some(types::PaymentsAuthorizeData {
amount: 310,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -323,9 +305,7 @@ async fn should_make_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
- txn_id.clone(),
- ),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
@@ -347,9 +327,7 @@ async fn should_sync_auto_captured_payment() {
.make_payment(
Some(types::PaymentsAuthorizeData {
amount: 311,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
@@ -364,7 +342,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -402,7 +380,7 @@ async fn should_fail_payment_for_empty_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("").unwrap(),
..utils::CCardType::default().0
}),
@@ -425,7 +403,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -448,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -470,7 +448,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
@@ -493,9 +471,7 @@ async fn should_fail_void_payment_for_auto_capture() {
.make_payment(
Some(types::PaymentsAuthorizeData {
amount: 307,
- payment_method_data: types::domain::PaymentMethodData::Card(
- get_payment_method_data(),
- ),
+ payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs
index 5cd82d097aa..3115c1143d7 100644
--- a/crates/router/tests/connectors/bambora.rs
+++ b/crates/router/tests/connectors/bambora.rs
@@ -40,7 +40,7 @@ static CONNECTOR: BamboraTest = BamboraTest {};
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
@@ -101,7 +101,7 @@ async fn should_sync_authorized_payment() {
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
mandate_id: None,
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -217,7 +217,7 @@ async fn should_sync_auto_captured_payment() {
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
mandate_id: None,
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -296,7 +296,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
card_exp_year: Secret::new("25".to_string()),
..utils::CCardType::default().0
@@ -319,7 +319,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
@@ -342,7 +342,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
@@ -367,7 +367,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_cvc: Secret::new("123".to_string()),
diff --git a/crates/router/tests/connectors/bankofamerica.rs b/crates/router/tests/connectors/bankofamerica.rs
index ca54e9c97b9..77085216dd5 100644
--- a/crates/router/tests/connectors/bankofamerica.rs
+++ b/crates/router/tests/connectors/bankofamerica.rs
@@ -93,7 +93,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -213,7 +213,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -303,7 +303,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -325,7 +325,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -347,7 +347,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/billwerk.rs b/crates/router/tests/connectors/billwerk.rs
index 6795aa40115..4c992ef3d92 100644
--- a/crates/router/tests/connectors/billwerk.rs
+++ b/crates/router/tests/connectors/billwerk.rs
@@ -93,7 +93,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -213,7 +213,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs
index df82775d6cf..85b388f2fdb 100644
--- a/crates/router/tests/connectors/bitpay.rs
+++ b/crates/router/tests/connectors/bitpay.rs
@@ -10,12 +10,12 @@ use crate::{
struct BitpayTest;
impl ConnectorActions for BitpayTest {}
impl utils::Connector for BitpayTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Bitpay;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Bitpay),
connector_name: types::Connector::Bitpay,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -67,7 +67,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
+ payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
}),
confirm: true,
@@ -126,7 +126,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"NPf27TDfyU5mhcTCw2oaq4".to_string(),
),
..Default::default()
@@ -145,7 +145,7 @@ async fn should_sync_expired_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"bUsFf4RjQEahjbjGcETRS".to_string(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs
index 2e02f259341..3a654eda839 100644
--- a/crates/router/tests/connectors/bluesnap.rs
+++ b/crates/router/tests/connectors/bluesnap.rs
@@ -121,7 +121,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -261,7 +261,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -401,7 +401,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
.make_payment(
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -426,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
.make_payment(
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -451,7 +451,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
.make_payment(
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/boku.rs b/crates/router/tests/connectors/boku.rs
index 2f496562e1d..f361a2365d5 100644
--- a/crates/router/tests/connectors/boku.rs
+++ b/crates/router/tests/connectors/boku.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs
index 616a080699b..025d9cdac64 100644
--- a/crates/router/tests/connectors/cashtocode.rs
+++ b/crates/router/tests/connectors/cashtocode.rs
@@ -39,7 +39,7 @@ static CONNECTOR: CashtocodeTest = CashtocodeTest {};
impl CashtocodeTest {
fn get_payment_authorize_data(
payment_method_type: Option<enums::PaymentMethodType>,
- payment_method_data: types::domain::PaymentMethodData,
+ payment_method_data: domain::PaymentMethodData,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1000,
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index 85b55afc8ea..886239878f2 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -97,7 +97,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -223,7 +223,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -320,7 +320,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -343,7 +343,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -366,7 +366,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs
index 0136284c826..0bcb3c705ab 100644
--- a/crates/router/tests/connectors/coinbase.rs
+++ b/crates/router/tests/connectors/coinbase.rs
@@ -11,12 +11,12 @@ use crate::{
struct CoinbaseTest;
impl ConnectorActions for CoinbaseTest {}
impl utils::Connector for CoinbaseTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Coinbase;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Coinbase),
connector_name: types::Connector::Coinbase,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -69,7 +69,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
+ payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
}),
confirm: true,
@@ -128,7 +128,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"ADFY3789".to_string(),
),
..Default::default()
@@ -147,7 +147,7 @@ async fn should_sync_unresolved_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"YJ6RFZXZ".to_string(),
),
..Default::default()
@@ -166,7 +166,7 @@ async fn should_sync_expired_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"FZ89KDDB".to_string(),
),
..Default::default()
@@ -185,7 +185,7 @@ async fn should_sync_cancelled_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"C35AAXKF".to_string(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs
index 56c0e29f621..626c05fe114 100644
--- a/crates/router/tests/connectors/cryptopay.rs
+++ b/crates/router/tests/connectors/cryptopay.rs
@@ -10,12 +10,12 @@ use crate::{
struct CryptopayTest;
impl ConnectorActions for CryptopayTest {}
impl utils::Connector for CryptopayTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Cryptopay;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Cryptopay),
connector_name: types::Connector::Cryptopay,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -68,7 +68,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
+ payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: Some("XRP".to_string()),
}),
confirm: true,
@@ -126,7 +126,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"ea684036-2b54-44fa-bffe-8256650dce7c".to_string(),
),
..Default::default()
@@ -145,7 +145,7 @@ async fn should_sync_unresolved_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"7993d4c2-efbc-4360-b8ce-d1e957e6f827".to_string(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs
index 98ec44abd8a..700e9a2d946 100644
--- a/crates/router/tests/connectors/cybersource.rs
+++ b/crates/router/tests/connectors/cybersource.rs
@@ -2,10 +2,7 @@ use std::str::FromStr;
use common_utils::pii::Email;
use masking::Secret;
-use router::types::{
- self, api, domain,
- storage::{self, enums},
-};
+use router::types::{self, api, domain, storage::enums};
use crate::{
connector_auth,
@@ -14,12 +11,12 @@ use crate::{
struct Cybersource;
impl ConnectorActions for Cybersource {}
impl utils::Connector for Cybersource {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Cybersource;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Cybersource),
connector_name: types::Connector::Cybersource,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -64,7 +61,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
}
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- currency: storage::enums::Currency::USD,
+ currency: enums::Currency::USD,
email: Some(Email::from_str("abc@gmail.com").unwrap()),
..PaymentAuthorizeType::default().0
})
@@ -127,7 +124,7 @@ async fn should_sync_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"6699597903496176903954".to_string(),
),
..Default::default()
@@ -160,7 +157,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = Cybersource {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("13".to_string()),
..utils::CCardType::default().0
}),
@@ -185,7 +182,7 @@ async fn should_fail_payment_for_invalid_exp_year() {
let response = Cybersource {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2022".to_string()),
..utils::CCardType::default().0
}),
@@ -203,7 +200,7 @@ async fn should_fail_payment_for_invalid_card_cvc() {
let response = Cybersource {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("2131233213".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs
index edb24646bcb..b715e20fec4 100644
--- a/crates/router/tests/connectors/dlocal.rs
+++ b/crates/router/tests/connectors/dlocal.rs
@@ -13,12 +13,12 @@ use crate::{
struct DlocalTest;
impl ConnectorActions for DlocalTest {}
impl utils::Connector for DlocalTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Dlocal;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Dlocal),
connector_name: types::Connector::Dlocal,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -89,7 +89,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -200,7 +200,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -289,7 +289,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1891011").unwrap(),
..utils::CCardType::default().0
}),
@@ -310,7 +310,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("1ad2345".to_string()),
..utils::CCardType::default().0
}),
@@ -331,7 +331,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("201".to_string()),
..utils::CCardType::default().0
}),
@@ -352,7 +352,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("20001".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/dummyconnector.rs b/crates/router/tests/connectors/dummyconnector.rs
index 76f72b64907..e357eda94c4 100644
--- a/crates/router/tests/connectors/dummyconnector.rs
+++ b/crates/router/tests/connectors/dummyconnector.rs
@@ -95,7 +95,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -215,7 +215,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -305,7 +305,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
@@ -327,7 +327,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -349,7 +349,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -371,7 +371,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/ebanx.rs b/crates/router/tests/connectors/ebanx.rs
index 8571ed1e3f8..6f02c80ebde 100644
--- a/crates/router/tests/connectors/ebanx.rs
+++ b/crates/router/tests/connectors/ebanx.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs
index 050d6a54067..f95c0d276ec 100644
--- a/crates/router/tests/connectors/fiserv.rs
+++ b/crates/router/tests/connectors/fiserv.rs
@@ -42,7 +42,7 @@ impl utils::Connector for FiservTest {
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4005550000000019").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
@@ -52,7 +52,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
@@ -123,7 +123,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -252,7 +252,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -347,7 +347,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
@@ -370,7 +370,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -393,7 +393,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -416,7 +416,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index c58cab38a22..1c99c2ff7b5 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -13,12 +13,12 @@ use crate::{
struct ForteTest;
impl ConnectorActions for ForteTest {}
impl utils::Connector for ForteTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Forte;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Forte),
connector_name: types::Connector::Forte,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -41,7 +41,7 @@ static CONNECTOR: ForteTest = ForteTest {};
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
@@ -148,7 +148,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -319,7 +319,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -467,7 +467,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -489,7 +489,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -512,7 +512,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
@@ -630,7 +630,7 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() {
#[actix_web::test]
async fn should_throw_not_implemented_for_unsupported_issuer() {
let authorize_data = Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("6759649826438453").unwrap(),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs
index e2ca19869f5..8ca4d6f1ae3 100644
--- a/crates/router/tests/connectors/globalpay.rs
+++ b/crates/router/tests/connectors/globalpay.rs
@@ -13,12 +13,12 @@ struct Globalpay;
impl ConnectorActions for Globalpay {}
static CONNECTOR: Globalpay = Globalpay {};
impl Connector for Globalpay {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Globalpay;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Globalpay),
connector_name: types::Connector::Globalpay,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -42,7 +42,7 @@ impl Connector for Globalpay {
}
fn get_access_token() -> Option<AccessToken> {
- match utils::Connector::get_auth_token(&CONNECTOR) {
+ match Connector::get_auth_token(&CONNECTOR) {
ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken {
token: api_key,
expires: 18600,
@@ -120,7 +120,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -137,7 +137,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
@@ -345,7 +345,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
@@ -367,7 +367,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -410,7 +410,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/globepay.rs b/crates/router/tests/connectors/globepay.rs
index 70167970210..34a2ecb4c88 100644
--- a/crates/router/tests/connectors/globepay.rs
+++ b/crates/router/tests/connectors/globepay.rs
@@ -94,7 +94,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -214,7 +214,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -304,7 +304,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -326,7 +326,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -348,7 +348,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/gocardless.rs b/crates/router/tests/connectors/gocardless.rs
index 0564ea7da6d..f7f2ed864bf 100644
--- a/crates/router/tests/connectors/gocardless.rs
+++ b/crates/router/tests/connectors/gocardless.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/helcim.rs b/crates/router/tests/connectors/helcim.rs
index dc3bb4d47e6..7bb4b9ab785 100644
--- a/crates/router/tests/connectors/helcim.rs
+++ b/crates/router/tests/connectors/helcim.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/iatapay.rs b/crates/router/tests/connectors/iatapay.rs
index d685756094e..dfb8e097be3 100644
--- a/crates/router/tests/connectors/iatapay.rs
+++ b/crates/router/tests/connectors/iatapay.rs
@@ -12,12 +12,12 @@ use crate::{
struct IatapayTest;
impl ConnectorActions for IatapayTest {}
impl Connector for IatapayTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Iatapay;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Iatapay),
connector_name: types::Connector::Iatapay,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -155,7 +155,7 @@ async fn should_sync_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"PE9OTYNP639XW".to_string(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index eb1c00a227b..78e67b7670a 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -62,6 +62,7 @@ mod trustpay;
mod tsys;
mod utils;
mod volt;
+#[cfg(feature = "payouts")]
mod wise;
mod worldline;
mod worldpay;
diff --git a/crates/router/tests/connectors/mollie.rs b/crates/router/tests/connectors/mollie.rs
index 14c77e2a9f0..be0b5d1c1d7 100644
--- a/crates/router/tests/connectors/mollie.rs
+++ b/crates/router/tests/connectors/mollie.rs
@@ -5,6 +5,7 @@ use crate::{
utils::{self, ConnectorActions},
};
+#[allow(dead_code)]
#[derive(Clone, Copy)]
struct MollieTest;
impl ConnectorActions for MollieTest {}
diff --git a/crates/router/tests/connectors/multisafepay.rs b/crates/router/tests/connectors/multisafepay.rs
index f35fe05bf36..606b60b2490 100644
--- a/crates/router/tests/connectors/multisafepay.rs
+++ b/crates/router/tests/connectors/multisafepay.rs
@@ -59,7 +59,7 @@ fn get_default_payment_info() -> Option<PaymentInfo> {
));
Some(PaymentInfo {
address,
- ..utils::PaymentInfo::default()
+ ..PaymentInfo::default()
})
}
@@ -121,7 +121,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -237,7 +237,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -331,7 +331,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("123498765".to_string()),
..utils::CCardType::default().0
}),
@@ -350,7 +350,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -369,7 +369,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/netcetera.rs b/crates/router/tests/connectors/netcetera.rs
index f06e2a0f5d7..d7fceca9c5d 100644
--- a/crates/router/tests/connectors/netcetera.rs
+++ b/crates/router/tests/connectors/netcetera.rs
@@ -91,7 +91,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -211,7 +211,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs
index 5948855ae8d..cdf94113c5a 100644
--- a/crates/router/tests/connectors/nexinets.rs
+++ b/crates/router/tests/connectors/nexinets.rs
@@ -41,7 +41,7 @@ impl utils::Connector for NexinetsTest {
fn payment_method_details() -> Option<PaymentsAuthorizeData> {
Some(PaymentsAuthorizeData {
currency: diesel_models::enums::Currency::EUR,
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("374111111111111").unwrap(),
..utils::CCardType::default().0
}),
@@ -118,7 +118,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
sync_type: types::SyncRequestType::SinglePaymentSync,
@@ -341,7 +341,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
capture_method: Some(enums::CaptureMethod::Automatic),
connector_meta,
..Default::default()
@@ -506,7 +506,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -528,7 +528,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -550,7 +550,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/nmi.rs b/crates/router/tests/connectors/nmi.rs
index 5b569fa497f..1d719e052a0 100644
--- a/crates/router/tests/connectors/nmi.rs
+++ b/crates/router/tests/connectors/nmi.rs
@@ -38,7 +38,7 @@ static CONNECTOR: NmiTest = NmiTest {};
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
@@ -60,10 +60,10 @@ async fn should_only_authorize_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -87,10 +87,10 @@ async fn should_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -110,10 +110,10 @@ async fn should_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -136,10 +136,10 @@ async fn should_partially_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -167,10 +167,10 @@ async fn should_partially_capture_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -194,10 +194,10 @@ async fn should_void_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -223,10 +223,10 @@ async fn should_void_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Voided,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -250,10 +250,10 @@ async fn should_refund_manually_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -273,10 +273,10 @@ async fn should_refund_manually_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -319,10 +319,10 @@ async fn should_partially_refund_manually_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -349,10 +349,10 @@ async fn should_partially_refund_manually_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -402,10 +402,10 @@ async fn should_make_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Automatic),
+ capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
@@ -429,10 +429,10 @@ async fn should_refund_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Automatic),
+ capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
@@ -475,10 +475,10 @@ async fn should_partially_refund_succeeded_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Automatic),
+ capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
@@ -528,10 +528,10 @@ async fn should_refund_succeeded_payment_multiple_times() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Automatic),
+ capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
@@ -600,10 +600,10 @@ async fn should_fail_void_payment_for_auto_capture() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Automatic),
+ capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
@@ -633,10 +633,10 @@ async fn should_fail_capture_for_invalid_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Manual),
+ capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
@@ -665,10 +665,10 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
- capture_method: Some(types::storage::enums::CaptureMethod::Automatic),
+ capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
diff --git a/crates/router/tests/connectors/noon.rs b/crates/router/tests/connectors/noon.rs
index 7e0bb954c6c..47e76d5ec76 100644
--- a/crates/router/tests/connectors/noon.rs
+++ b/crates/router/tests/connectors/noon.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use masking::Secret;
-use router::types::{
- self,
- storage::{self, enums},
-};
+use router::types::{self, storage::enums};
use crate::{
connector_auth,
@@ -47,7 +44,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- currency: storage::enums::Currency::AED,
+ currency: enums::Currency::AED,
..utils::PaymentAuthorizeType::default().0
})
}
@@ -102,7 +99,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -222,7 +219,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs
index 04a83b3a606..55a8f234219 100644
--- a/crates/router/tests/connectors/nuvei.rs
+++ b/crates/router/tests/connectors/nuvei.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use masking::Secret;
-use router::types::{
- self,
- storage::{self, enums},
-};
+use router::types::{self, storage::enums};
use serde_json::json;
use crate::{
@@ -102,7 +99,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
connector_meta: Some(json!({
@@ -126,7 +123,7 @@ async fn should_void_authorized_payment() {
Some(types::PaymentsCancelData {
cancellation_reason: Some("requested_by_customer".to_string()),
amount: Some(100),
- currency: Some(storage::enums::Currency::USD),
+ currency: Some(enums::Currency::USD),
..Default::default()
}),
None,
@@ -194,7 +191,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
connector_meta: Some(json!({
@@ -345,7 +342,7 @@ async fn should_fail_void_payment_for_auto_capture() {
Some(types::PaymentsCancelData {
cancellation_reason: Some("requested_by_customer".to_string()),
amount: Some(100),
- currency: Some(storage::enums::Currency::USD),
+ currency: Some(enums::Currency::USD),
..Default::default()
}),
None,
diff --git a/crates/router/tests/connectors/opayo.rs b/crates/router/tests/connectors/opayo.rs
index f4badf9b116..b383a2e1b0e 100644
--- a/crates/router/tests/connectors/opayo.rs
+++ b/crates/router/tests/connectors/opayo.rs
@@ -97,7 +97,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -217,7 +217,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -307,7 +307,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
@@ -329,7 +329,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -351,7 +351,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -373,7 +373,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs
index e4d347c26d1..c91126953de 100644
--- a/crates/router/tests/connectors/opennode.rs
+++ b/crates/router/tests/connectors/opennode.rs
@@ -10,12 +10,12 @@ use crate::{
struct OpennodeTest;
impl ConnectorActions for OpennodeTest {}
impl utils::Connector for OpennodeTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Opennode;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Opennode),
connector_name: types::Connector::Opennode,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -68,7 +68,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
+ payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
}),
confirm: true,
@@ -127,7 +127,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(),
),
..Default::default()
@@ -146,7 +146,7 @@ async fn should_sync_unresolved_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"4cf63e6b-5135-49cb-997f-6e0b30fecebc".to_string(),
),
..Default::default()
@@ -165,7 +165,7 @@ async fn should_sync_expired_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"c36a097a-5091-4317-8749-80343a71c1c4".to_string(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs
index a1682001488..234f3a0eeb8 100644
--- a/crates/router/tests/connectors/payme.rs
+++ b/crates/router/tests/connectors/payme.rs
@@ -91,7 +91,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("test@gmail.com").unwrap()),
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_cvc: Secret::new("123".to_string()),
card_exp_month: Secret::new("10".to_string()),
@@ -155,7 +155,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -280,7 +280,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -372,7 +372,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
Some(types::PaymentsAuthorizeData {
amount: 100,
currency: enums::Currency::ILS,
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -391,7 +391,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("test@gmail.com").unwrap()),
- ..utils::PaymentAuthorizeType::default().0
+ ..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
@@ -411,7 +411,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
Some(types::PaymentsAuthorizeData {
amount: 100,
currency: enums::Currency::ILS,
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -430,7 +430,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("test@gmail.com").unwrap()),
- ..utils::PaymentAuthorizeType::default().0
+ ..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
@@ -450,7 +450,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
Some(types::PaymentsAuthorizeData {
amount: 100,
currency: enums::Currency::ILS,
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2012".to_string()),
..utils::CCardType::default().0
}),
@@ -469,7 +469,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
email: Some(Email::from_str("test@gmail.com").unwrap()),
- ..utils::PaymentAuthorizeType::default().0
+ ..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs
index bded135f45d..704aeca5936 100644
--- a/crates/router/tests/connectors/paypal.rs
+++ b/crates/router/tests/connectors/paypal.rs
@@ -56,7 +56,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4000020000000000").unwrap(),
..utils::CCardType::default().0
}),
@@ -136,7 +136,7 @@ async fn should_sync_authorized_payment() {
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
mandate_id: None,
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id),
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
sync_type: types::SyncRequestType::SinglePaymentSync,
@@ -332,7 +332,7 @@ async fn should_sync_auto_captured_payment() {
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
mandate_id: None,
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -450,7 +450,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -476,7 +476,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -502,7 +502,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs
index fc916e33677..2f6ebcefe6a 100644
--- a/crates/router/tests/connectors/payu.rs
+++ b/crates/router/tests/connectors/payu.rs
@@ -70,7 +70,7 @@ async fn should_authorize_card_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
@@ -115,7 +115,7 @@ async fn should_authorize_gpay_payment() {
let sync_response = Payu {}
.sync_payment(
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
@@ -148,7 +148,7 @@ async fn should_capture_already_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
@@ -167,7 +167,7 @@ async fn should_capture_already_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id,
),
..Default::default()
@@ -203,7 +203,7 @@ async fn should_sync_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id,
),
..Default::default()
@@ -246,7 +246,7 @@ async fn should_void_already_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Voided,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id,
),
..Default::default()
@@ -280,7 +280,7 @@ async fn should_refund_succeeded_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
@@ -301,7 +301,7 @@ async fn should_refund_succeeded_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/placetopay.rs b/crates/router/tests/connectors/placetopay.rs
index 41675b9751b..d9b75cbe0e8 100644
--- a/crates/router/tests/connectors/placetopay.rs
+++ b/crates/router/tests/connectors/placetopay.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/powertranz.rs b/crates/router/tests/connectors/powertranz.rs
index 0701ec006d9..7f1e1937e05 100644
--- a/crates/router/tests/connectors/powertranz.rs
+++ b/crates/router/tests/connectors/powertranz.rs
@@ -96,7 +96,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -218,7 +218,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -310,7 +310,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -332,7 +332,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -354,7 +354,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/prophetpay.rs b/crates/router/tests/connectors/prophetpay.rs
index 9a0e2dbfa0e..5e326c0bcd3 100644
--- a/crates/router/tests/connectors/prophetpay.rs
+++ b/crates/router/tests/connectors/prophetpay.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs
index 61bc7ccdf15..4b5357c51ec 100644
--- a/crates/router/tests/connectors/rapyd.rs
+++ b/crates/router/tests/connectors/rapyd.rs
@@ -42,7 +42,7 @@ async fn should_only_authorize_payment() {
let response = Rapyd {}
.authorize_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2024".to_string()),
@@ -52,7 +52,7 @@ async fn should_only_authorize_payment() {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
@@ -69,7 +69,7 @@ async fn should_authorize_and_capture_payment() {
let response = Rapyd {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2024".to_string()),
@@ -79,7 +79,7 @@ async fn should_authorize_and_capture_payment() {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
..utils::PaymentAuthorizeType::default().0
}),
@@ -157,7 +157,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = Rapyd {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("0000000000000000").unwrap(),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs
index 8f11fbfa1d8..632e5389351 100644
--- a/crates/router/tests/connectors/shift4.rs
+++ b/crates/router/tests/connectors/shift4.rs
@@ -90,7 +90,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -114,7 +114,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -151,7 +151,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
@@ -173,7 +173,7 @@ async fn should_succeed_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("asdasd".to_string()), //shift4 accept invalid CVV as it doesn't accept CVV
..utils::CCardType::default().0
}),
@@ -192,7 +192,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -214,7 +214,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs
index 01d90c73c42..2dcd93cc105 100644
--- a/crates/router/tests/connectors/square.rs
+++ b/crates/router/tests/connectors/square.rs
@@ -1,11 +1,7 @@
use std::{str::FromStr, time::Duration};
use masking::Secret;
-use router::types::{
- self,
- storage::{self, enums},
- PaymentsResponseData,
-};
+use router::types::{self, storage::enums, PaymentsResponseData};
use test_utils::connector_auth::ConnectorAuthentication;
use crate::utils::{self, get_connector_transaction_id, Connector, ConnectorActions};
@@ -71,7 +67,7 @@ fn token_details() -> Option<types::PaymentMethodTokenizationData> {
}),
browser_info: None,
amount: None,
- currency: storage::enums::Currency::USD,
+ currency: enums::Currency::USD,
})
}
@@ -147,7 +143,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -291,7 +287,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -444,7 +440,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
}),
browser_info: None,
amount: None,
- currency: storage::enums::Currency::USD,
+ currency: enums::Currency::USD,
}),
get_default_payment_info(None),
)
@@ -475,7 +471,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
}),
browser_info: None,
amount: None,
- currency: storage::enums::Currency::USD,
+ currency: enums::Currency::USD,
}),
get_default_payment_info(None),
)
@@ -506,7 +502,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
}),
browser_info: None,
amount: None,
- currency: storage::enums::Currency::USD,
+ currency: enums::Currency::USD,
}),
get_default_payment_info(None),
)
diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs
index d16f209a49a..421ad9524c3 100644
--- a/crates/router/tests/connectors/stax.rs
+++ b/crates/router/tests/connectors/stax.rs
@@ -63,7 +63,7 @@ fn customer_details() -> Option<types::ConnectorCustomerData> {
fn token_details() -> Option<types::PaymentMethodTokenizationData> {
Some(types::PaymentMethodTokenizationData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("04".to_string()),
card_exp_year: Secret::new("2027".to_string()),
@@ -167,7 +167,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -344,7 +344,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -473,7 +473,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let token_response = CONNECTOR
.create_connector_pm_token(
Some(types::PaymentMethodTokenizationData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("11".to_string()),
card_exp_year: Secret::new("2027".to_string()),
@@ -511,7 +511,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let token_response = CONNECTOR
.create_connector_pm_token(
Some(types::PaymentMethodTokenizationData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("20".to_string()),
card_exp_year: Secret::new("2027".to_string()),
@@ -549,7 +549,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let token_response = CONNECTOR
.create_connector_pm_token(
Some(types::PaymentMethodTokenizationData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("04".to_string()),
card_exp_year: Secret::new("2000".to_string()),
diff --git a/crates/router/tests/connectors/stripe.rs b/crates/router/tests/connectors/stripe.rs
index 3dcaeba45b0..2d6b3e0cfd3 100644
--- a/crates/router/tests/connectors/stripe.rs
+++ b/crates/router/tests/connectors/stripe.rs
@@ -37,7 +37,7 @@ impl utils::Connector for Stripe {
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4242424242424242").unwrap(),
..utils::CCardType::default().0
}),
@@ -100,7 +100,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -124,7 +124,7 @@ async fn should_sync_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -158,7 +158,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
@@ -180,7 +180,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("13".to_string()),
..utils::CCardType::default().0
}),
@@ -202,7 +202,7 @@ async fn should_fail_payment_for_invalid_exp_year() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2022".to_string()),
..utils::CCardType::default().0
}),
@@ -221,7 +221,7 @@ async fn should_fail_payment_for_invalid_card_cvc() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs
index 48cd165767c..fba612863b4 100644
--- a/crates/router/tests/connectors/trustpay.rs
+++ b/crates/router/tests/connectors/trustpay.rs
@@ -12,12 +12,12 @@ use crate::{
struct TrustpayTest;
impl ConnectorActions for TrustpayTest {}
impl utils::Connector for TrustpayTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Trustpay;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Trustpay),
connector_name: types::Connector::Trustpay,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
@@ -53,7 +53,7 @@ fn get_default_browser_info() -> BrowserInformation {
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
@@ -122,7 +122,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -182,7 +182,7 @@ async fn should_sync_refund() {
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let payment_authorize_data = types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
@@ -205,7 +205,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let payment_authorize_data = Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_year: Secret::new("22".to_string()),
card_cvc: Secret::new("123".to_string()),
diff --git a/crates/router/tests/connectors/tsys.rs b/crates/router/tests/connectors/tsys.rs
index d7a688bd128..ef4f576ad9e 100644
--- a/crates/router/tests/connectors/tsys.rs
+++ b/crates/router/tests/connectors/tsys.rs
@@ -46,7 +46,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
fn payment_method_details(amount: i64) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount,
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
@@ -108,7 +108,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -244,7 +244,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("".to_string()),
..utils::CCardType::default().0
}),
@@ -368,7 +368,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -390,7 +390,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("abcd".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 9678eca73f3..3196c4c763b 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -8,7 +8,7 @@ use masking::Secret;
use router::core::utils as core_utils;
use router::{
configs::settings::Settings,
- core::{errors, errors::ConnectorError, payments},
+ core::{errors::ConnectorError, payments},
db::StorageImpl,
routes, services,
types::{self, storage::enums, AccessToken, PaymentAddress, RouterData},
@@ -57,7 +57,7 @@ pub struct PaymentInfo {
impl PaymentInfo {
pub fn with_default_billing_name() -> Self {
Self {
- address: Some(types::PaymentAddress::new(
+ address: Some(PaymentAddress::new(
None,
None,
Some(types::api::Address {
@@ -215,7 +215,7 @@ pub trait ConnectorActions: Connector {
}
tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await;
}
- Err(errors::ConnectorError::ProcessingStepFailed(None).into())
+ Err(ConnectorError::ProcessingStepFailed(None).into())
}
async fn capture_payment(
@@ -453,7 +453,7 @@ pub trait ConnectorActions: Connector {
}
tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await;
}
- Err(errors::ConnectorError::ProcessingStepFailed(None).into())
+ Err(ConnectorError::ProcessingStepFailed(None).into())
}
#[cfg(feature = "payouts")]
@@ -523,7 +523,7 @@ pub trait ConnectorActions: Connector {
.unwrap(),
connector_meta_data: info
.clone()
- .and_then(|a| a.connector_meta_data.map(masking::Secret::new)),
+ .and_then(|a| a.connector_meta_data.map(Secret::new)),
amount_captured: None,
access_token: info.clone().and_then(|a| a.access_token),
session_token: None,
@@ -902,7 +902,7 @@ impl Default for CCardType {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
})
}
}
diff --git a/crates/router/tests/connectors/volt.rs b/crates/router/tests/connectors/volt.rs
index 7bcdf63d918..efe6d603e70 100644
--- a/crates/router/tests/connectors/volt.rs
+++ b/crates/router/tests/connectors/volt.rs
@@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
@@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
@@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rs
index b85fb4f1c96..fd5bbc109d9 100644
--- a/crates/router/tests/connectors/wise.rs
+++ b/crates/router/tests/connectors/wise.rs
@@ -1,38 +1,36 @@
-#[cfg(feature = "payouts")]
use api_models::payments::{Address, AddressDetails};
-#[cfg(feature = "payouts")]
use masking::Secret;
-use router::types;
-#[cfg(feature = "payouts")]
-use router::types::{api, storage::enums, PaymentAddress};
+use router::{
+ types,
+ types::{api, storage::enums, PaymentAddress},
+};
-#[cfg(feature = "payouts")]
-use crate::utils::PaymentInfo;
use crate::{
connector_auth,
- utils::{self, ConnectorActions},
+ utils::{self, ConnectorActions, PaymentInfo},
};
struct WiseTest;
+
impl ConnectorActions for WiseTest {}
+
impl utils::Connector for WiseTest {
- fn get_data(&self) -> types::api::ConnectorData {
+ fn get_data(&self) -> api::ConnectorData {
use router::connector::Adyen;
- types::api::ConnectorData {
+ api::ConnectorData {
connector: Box::new(&Adyen),
connector_name: types::Connector::Adyen,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
}
}
- #[cfg(feature = "payouts")]
- fn get_payout_data(&self) -> Option<types::api::ConnectorData> {
+ fn get_payout_data(&self) -> Option<api::ConnectorData> {
use router::connector::Wise;
- Some(types::api::ConnectorData {
+ Some(api::ConnectorData {
connector: Box::new(&Wise),
connector_name: types::Connector::Wise,
- get_token: types::api::GetToken::Connector,
+ get_token: api::GetToken::Connector,
merchant_connector_id: None,
})
}
@@ -52,7 +50,6 @@ impl utils::Connector for WiseTest {
}
impl WiseTest {
- #[cfg(feature = "payouts")]
fn get_payout_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
country: Some(api_models::enums::CountryAlpha2::NL),
@@ -86,12 +83,11 @@ impl WiseTest {
}
}
-#[cfg(feature = "payouts")]
static CONNECTOR: WiseTest = WiseTest {};
/******************** Payouts test cases ********************/
// Creates a recipient at connector's end
-#[cfg(feature = "payouts")]
+
#[actix_web::test]
async fn should_create_payout_recipient() {
let payout_type = enums::PayoutType::Bank;
@@ -107,7 +103,7 @@ async fn should_create_payout_recipient() {
}
// Create BACS payout
-#[cfg(feature = "payouts")]
+
#[actix_web::test]
async fn should_create_bacs_payout() {
let payout_type = enums::PayoutType::Bank;
@@ -138,7 +134,7 @@ async fn should_create_bacs_payout() {
}
// Create and fulfill BACS payout
-#[cfg(feature = "payouts")]
+
#[actix_web::test]
async fn should_create_and_fulfill_bacs_payout() {
let payout_type = enums::PayoutType::Bank;
diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs
index 21a5a574122..4f8119bfc52 100644
--- a/crates/router/tests/connectors/worldline.rs
+++ b/crates/router/tests/connectors/worldline.rs
@@ -81,7 +81,7 @@ impl WorldlineTest {
card_type: None,
card_issuing_country: None,
bank_code: None,
- nick_name: Some(masking::Secret::new("nick_name".into())),
+ nick_name: Some(Secret::new("nick_name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
@@ -231,7 +231,7 @@ async fn should_sync_manual_auth_payment() {
let sync_response = connector
.sync_payment(
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
connector_payment_id,
),
capture_method: Some(enums::CaptureMethod::Manual),
@@ -264,7 +264,7 @@ async fn should_sync_auto_auth_payment() {
let sync_response = connector
.sync_payment(
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
connector_payment_id,
),
capture_method: Some(enums::CaptureMethod::Automatic),
diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs
index 649b1bebbb1..571de7d959d 100644
--- a/crates/router/tests/connectors/worldpay.rs
+++ b/crates/router/tests/connectors/worldpay.rs
@@ -62,7 +62,7 @@ async fn should_authorize_gpay_payment() {
let response = conn
.authorize_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Wallet(
+ payment_method_data: domain::PaymentMethodData::Wallet(
domain::WalletData::GooglePay(domain::GooglePayWalletData {
pm_type: "CARD".to_string(),
description: "Visa1234567890".to_string(),
@@ -97,7 +97,7 @@ async fn should_authorize_applepay_payment() {
let response = conn
.authorize_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Wallet(
+ payment_method_data: domain::PaymentMethodData::Wallet(
domain::WalletData::ApplePay(domain::ApplePayWalletData {
payment_data: "someData".to_string(),
transaction_identifier: "someId".to_string(),
@@ -149,7 +149,7 @@ async fn should_sync_payment() {
let response = connector
.sync_payment(
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"112233".to_string(),
),
..Default::default()
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index e076aee42c4..b11b78025d0 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -95,7 +95,7 @@ async fn should_sync_authorized_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -211,7 +211,7 @@ async fn should_sync_auto_captured_payment() {
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
- connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
@@ -310,7 +310,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
@@ -352,7 +352,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -394,7 +394,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -436,7 +436,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
- payment_method_data: types::domain::PaymentMethodData::Card(domain::Card {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 646a11d4cdd..f4325d01b90 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -26,7 +26,7 @@ use uuid::Uuid;
async fn payments_create_stripe() {
Box::pin(utils::setup()).await;
- let payment_id = format!("test_{}", uuid::Uuid::new_v4());
+ let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let request = serde_json::json!({
@@ -95,7 +95,7 @@ async fn payments_create_stripe() {
async fn payments_create_adyen() {
Box::pin(utils::setup()).await;
- let payment_id = format!("test_{}", uuid::Uuid::new_v4());
+ let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "321");
let request = serde_json::json!({
@@ -164,7 +164,7 @@ async fn payments_create_adyen() {
async fn payments_create_fail() {
Box::pin(utils::setup()).await;
- let payment_id = format!("test_{}", uuid::Uuid::new_v4());
+ let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let invalid_request = serde_json::json!({
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 9b622d11fd1..56ab453a0f5 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -14,7 +14,7 @@ use uuid::Uuid;
#[test]
fn connector_list() {
- let connector_list = router::types::ConnectorsList {
+ let connector_list = types::ConnectorsList {
connectors: vec![String::from("stripe"), "adyen".to_string()],
};
@@ -22,7 +22,7 @@ fn connector_list() {
println!("{}", &json);
- let newlist: router::types::ConnectorsList = serde_json::from_str(&json).unwrap();
+ let newlist: types::ConnectorsList = serde_json::from_str(&json).unwrap();
println!("{newlist:#?}");
assert_eq!(true, true);
@@ -125,7 +125,7 @@ async fn payments_create_core() {
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
- let actual_response = Box::pin(router::core::payments::payments_core::<
+ let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
@@ -316,7 +316,7 @@ async fn payments_create_core_adyen_no_redirect() {
},
vec![],
));
- let actual_response = Box::pin(router::core::payments::payments_core::<
+ let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
diff --git a/crates/router_derive/src/macros/api_error/helpers.rs b/crates/router_derive/src/macros/api_error/helpers.rs
index 5781d786ee5..deb1b349cb1 100644
--- a/crates/router_derive/src/macros/api_error/helpers.rs
+++ b/crates/router_derive/src/macros/api_error/helpers.rs
@@ -260,9 +260,9 @@ pub(super) fn get_unused_fields(
ignore: &std::collections::HashSet<String>,
) -> Vec<Field> {
let fields = match fields {
- syn::Fields::Unit => Vec::new(),
- syn::Fields::Unnamed(_) => Vec::new(),
- syn::Fields::Named(fields) => fields.named.iter().cloned().collect(),
+ Fields::Unit => Vec::new(),
+ Fields::Unnamed(_) => Vec::new(),
+ Fields::Named(fields) => fields.named.iter().cloned().collect(),
};
fields
.iter()
diff --git a/crates/router_derive/src/macros/helpers.rs b/crates/router_derive/src/macros/helpers.rs
index b6490c4d629..1cb7e21bb9d 100644
--- a/crates/router_derive/src/macros/helpers.rs
+++ b/crates/router_derive/src/macros/helpers.rs
@@ -58,7 +58,7 @@ pub(super) fn get_struct_fields(
Ok(named.to_owned())
} else {
Err(syn::Error::new(
- proc_macro2::Span::call_site(),
+ Span::call_site(),
"This macro cannot be used on structs with no fields",
))
}
diff --git a/crates/router_derive/src/macros/try_get_enum.rs b/crates/router_derive/src/macros/try_get_enum.rs
index f607b7f06c9..bdfbdb66938 100644
--- a/crates/router_derive/src/macros/try_get_enum.rs
+++ b/crates/router_derive/src/macros/try_get_enum.rs
@@ -68,7 +68,7 @@ pub fn try_get_enum_variant(
let try_into_fn = syn::Ident::new(
&format!("try_into_{}", variant_name.to_string().to_lowercase()),
- proc_macro2::Span::call_site(),
+ Span::call_site(),
);
Ok(quote::quote! {
diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs
index af77991e804..3a9e719db18 100644
--- a/crates/router_env/src/logger/setup.rs
+++ b/crates/router_env/src/logger/setup.rs
@@ -265,7 +265,7 @@ fn setup_tracing_pipeline(
.with_exporter(get_opentelemetry_exporter(config))
.with_batch_config(batch_config)
.with_trace_config(trace_config)
- .install_batch(opentelemetry::runtime::TokioCurrentThread)
+ .install_batch(runtime::TokioCurrentThread)
.map(|tracer| tracing_opentelemetry::layer().with_tracer(tracer));
if config.ignore_errors {
diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs
index fd2b9b654a4..397aab84e91 100644
--- a/crates/scheduler/src/producer.rs
+++ b/crates/scheduler/src/producer.rs
@@ -43,11 +43,10 @@ where
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,
- ));
+ let mut interval =
+ tokio::time::interval(Duration::from_millis(scheduler_settings.loop_interval));
- let mut shutdown_interval = tokio::time::interval(std::time::Duration::from_millis(
+ let mut shutdown_interval = tokio::time::interval(Duration::from_millis(
scheduler_settings.graceful_shutdown_interval,
));
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index 11924dd1be2..8b80b7c72c1 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -254,7 +254,7 @@ pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime
}
#[instrument(skip_all)]
-pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>(
+pub async fn consumer_operation_handler<E, T>(
state: T,
settings: sync::Arc<SchedulerSettings>,
error_handler_fun: E,
@@ -263,7 +263,7 @@ pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>(
) where
// Error handler function
E: FnOnce(error_stack::Report<errors::ProcessTrackerError>),
- T: SchedulerAppState,
+ T: SchedulerAppState + Send + Sync + 'static,
{
consumer_operation_counter.fetch_add(1, atomic::Ordering::SeqCst);
let start_time = std_time::Instant::now();
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 41099bea75f..4356b6b7997 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -8,7 +8,7 @@ use hyperswitch_domain_models::errors::StorageError as DataStorageError;
pub use redis_interface::errors::RedisError;
use router_env::opentelemetry::metrics::MetricsError;
-use crate::{errors as storage_errors, store::errors::DatabaseError};
+use crate::store::errors::DatabaseError;
pub type ApplicationResult<T> = Result<T, ApplicationError>;
@@ -56,20 +56,16 @@ impl Into<DataStorageError> for &StorageError {
fn into(self) -> DataStorageError {
match self {
StorageError::DatabaseError(i) => match i.current_context() {
- storage_errors::DatabaseError::DatabaseConnectionError => {
- DataStorageError::DatabaseConnectionError
- }
+ DatabaseError::DatabaseConnectionError => DataStorageError::DatabaseConnectionError,
// TODO: Update this error type to encompass & propagate the missing type (instead of generic `db value not found`)
- storage_errors::DatabaseError::NotFound => {
+ DatabaseError::NotFound => {
DataStorageError::ValueNotFound(String::from("db value not found"))
}
// TODO: Update this error type to encompass & propagate the duplicate type (instead of generic `db value not found`)
- storage_errors::DatabaseError::UniqueViolation => {
- DataStorageError::DuplicateValue {
- entity: "db entity",
- key: None,
- }
- }
+ DatabaseError::UniqueViolation => DataStorageError::DuplicateValue {
+ entity: "db entity",
+ key: None,
+ },
err => DataStorageError::DatabaseError(error_stack::report!(*err)),
},
StorageError::ValueNotFound(i) => DataStorageError::ValueNotFound(i.clone()),
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index e35d1f41511..7a3ef30bef3 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -217,7 +217,7 @@ impl<T: DatabaseStore> KVRouterStore<T> {
partition_key: redis::kv_store::PartitionKey<'_>,
) -> error_stack::Result<(), RedisError>
where
- R: crate::redis::kv_store::KvStorePartition,
+ R: redis::kv_store::KvStorePartition,
{
let global_id = format!("{}", partition_key);
let request_id = self.request_id.clone().unwrap_or_default();
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 5cf0123eb7b..3657201f878 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -41,9 +41,9 @@ pub struct MockDb {
pub disputes: Arc<Mutex<Vec<store::Dispute>>>,
pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>,
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>>>,
+ pub captures: Arc<Mutex<Vec<store::capture::Capture>>>,
+ pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>,
+ pub business_profiles: Arc<Mutex<Vec<store::business_profile::BusinessProfile>>>,
pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>,
pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>,
pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index fcc4ec63ff2..2cbcbaaf01e 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -257,7 +257,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, StorageError> {
match payment.active_attempt.clone() {
- hyperswitch_domain_models::RemoteStorageObject::ForeignID(attempt_id) => {
+ RemoteStorageObject::ForeignID(attempt_id) => {
let conn = pg_connection_read(self).await?;
let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
@@ -271,11 +271,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)?;
- payment.active_attempt =
- hyperswitch_domain_models::RemoteStorageObject::Object(pa.clone());
+ payment.active_attempt = RemoteStorageObject::Object(pa.clone());
Ok(pa)
}
- hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ RemoteStorageObject::Object(pa) => Ok(pa.clone()),
}
}
@@ -397,7 +396,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, StorageError> {
match &payment.active_attempt {
- hyperswitch_domain_models::RemoteStorageObject::ForeignID(attempt_id) => {
+ RemoteStorageObject::ForeignID(attempt_id) => {
let conn = pg_connection_read(self).await?;
let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
@@ -411,11 +410,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
er.change_context(new_err)
})
.map(PaymentAttempt::from_storage_model)?;
- payment.active_attempt =
- hyperswitch_domain_models::RemoteStorageObject::Object(pa.clone());
+ payment.active_attempt = RemoteStorageObject::Object(pa.clone());
Ok(pa)
}
- hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()),
+ RemoteStorageObject::Object(pa) => Ok(pa.clone()),
}
}
diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs
index e70c630cffe..c90292683ff 100644
--- a/crates/test_utils/src/newman_runner.rs
+++ b/crates/test_utils/src/newman_runner.rs
@@ -63,7 +63,7 @@ fn get_dir_path(name: impl AsRef<str>) -> String {
// This function currently allows you to add only custom headers.
// In future, as we scale, this can be modified based on the need
-fn insert_content<T, U>(dir: T, content_to_insert: U) -> std::io::Result<()>
+fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()>
where
T: AsRef<Path>,
U: AsRef<str>,
@@ -72,7 +72,7 @@ where
let file_path = dir.as_ref().join(file_name);
// Open the file in write mode or create it if it doesn't exist
- let mut file = std::fs::OpenOptions::new()
+ let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(file_path)?;
|
2024-05-03T14:36: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 -->
This PR addresses the clippy lints occurring due to new rust version 1.78
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
71a070e26989f080031d92a88aa0143836d1ea7b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4487
|
Bug: remove `configs/pg_agnostic_mit` api as it will not be used
Remove the configs/pg_agnostic_mit api as there is a new api added to enabled the same feature in this https://github.com/juspay/hyperswitch/pull/4480. Also includes changes to read the is_connector_agnostic_mit flow form the business profile.
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 723e6eccc36..f3d966f3d9d 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -299,13 +299,6 @@ impl From<RoutableConnectorChoice> for ast::ConnectorChoice {
}
}
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
-pub struct DetailedConnectorChoice {
- pub enabled: bool,
-}
-
-impl common_utils::events::ApiEventMetric for DetailedConnectorChoice {}
-
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 815c604a0e3..07bceefb0f9 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -314,6 +314,7 @@ where
&merchant_account,
&key_store,
&mut payment_data,
+ &business_profile,
)
.await?;
@@ -415,6 +416,7 @@ where
&merchant_account,
&key_store,
&mut payment_data,
+ &business_profile,
)
.await?;
@@ -3320,6 +3322,7 @@ where
routing_data,
connector_data,
mandate_type,
+ business_profile.is_connector_agnostic_mit_enabled,
)
.await;
}
@@ -3377,6 +3380,7 @@ where
routing_data,
connector_data,
mandate_type,
+ business_profile.is_connector_agnostic_mit_enabled,
)
.await;
}
@@ -3400,6 +3404,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorData>,
mandate_type: Option<api::MandateTransactionType>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
) -> RouterResult<ConnectorCallType> {
match (
payment_data.payment_intent.setup_future_usage,
@@ -3442,22 +3447,6 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize connector mandate details")?;
- let profile_id = payment_data
- .payment_intent
- .profile_id
- .as_ref()
- .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
-
- let pg_agnostic = state
- .store
- .find_config_by_key_unwrap_or(
- &format!("pg_agnostic_mandate_{}", profile_id),
- Some("false".to_string()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("The pg_agnostic config was not found in the DB")?;
-
let mut connector_choice = None;
for connector_data in connectors {
@@ -3468,7 +3457,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
if is_network_transaction_id_flow(
state,
- &pg_agnostic.config,
+ is_connector_agnostic_mit_enabled,
connector_data.connector_name,
payment_method_info,
) {
@@ -3588,7 +3577,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
pub fn is_network_transaction_id_flow(
state: &AppState,
- pg_agnostic: &String,
+ is_connector_agnostic_mit_enabled: Option<bool>,
connector: enums::Connector,
payment_method_info: &storage::PaymentMethod,
) -> bool {
@@ -3597,7 +3586,7 @@ pub fn is_network_transaction_id_flow(
.network_transaction_id_supported_connectors
.connector_list;
- pg_agnostic == "true"
+ is_connector_agnostic_mit_enabled == Some(true)
&& payment_method_info.payment_method == Some(storage_enums::PaymentMethod::Card)
&& ntid_supported_connectors.contains(&connector)
&& payment_method_info.network_transaction_id.is_some()
@@ -3827,6 +3816,7 @@ where
routing_data,
connector_data,
mandate_type,
+ business_profile.is_connector_agnostic_mit_enabled,
)
.await
}
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index c214decb0b4..da9a2108691 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -241,6 +241,7 @@ pub trait PostUpdateTracker<F, D, R: Send>: Send {
_merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
_payment_data: &mut PaymentData<F>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index f4408749fd3..b40ee8e5c9c 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -89,13 +89,13 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let customer_id = payment_data.payment_intent.customer_id.clone();
let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
- let profile_id = payment_data.payment_intent.profile_id.clone();
let connector_name = payment_data
.payment_attempt
@@ -125,8 +125,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
key_store,
Some(resp.request.amount),
Some(resp.request.currency),
- profile_id,
billing_name.clone(),
+ business_profile,
));
let is_connector_mandate = resp.request.customer_acceptance.is_some()
@@ -169,11 +169,12 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
let key_store = key_store.clone();
let state = state.clone();
let customer_id = payment_data.payment_intent.customer_id.clone();
- let profile_id = payment_data.payment_intent.profile_id.clone();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let payment_attempt = payment_data.payment_attempt.clone();
+ let business_profile = business_profile.clone();
+
let amount = resp.request.amount;
let currency = resp.request.currency;
let payment_method_type = resp.request.payment_method_type;
@@ -195,8 +196,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
&key_store,
Some(amount),
Some(currency),
- profile_id,
billing_name,
+ &business_profile,
))
.await;
@@ -388,6 +389,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
@@ -398,6 +400,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
resp.status,
resp.response.clone(),
merchant_account.storage_scheme,
+ business_profile.is_connector_agnostic_mit_enabled,
)
.await?;
Ok(())
@@ -587,6 +590,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
@@ -598,7 +602,6 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
.and_then(|address| address.get_optional_full_name());
let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
let customer_id = payment_data.payment_intent.customer_id.clone();
- let profile_id = payment_data.payment_intent.profile_id.clone();
let connector_name = payment_data
.payment_attempt
.connector
@@ -622,8 +625,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
key_store,
resp.request.amount,
Some(resp.request.currency),
- profile_id,
billing_name,
+ business_profile,
))
.await?;
@@ -674,6 +677,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
@@ -684,6 +688,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
resp.status,
resp.response.clone(),
merchant_account.storage_scheme,
+ business_profile.is_connector_agnostic_mit_enabled,
)
.await?;
Ok(())
@@ -1224,6 +1229,7 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
storage_scheme: enums::MerchantStorageScheme,
+ is_connector_agnostic_mit_enabled: Option<bool>,
) -> RouterResult<()> {
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
let pm = state
@@ -1244,23 +1250,7 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
let network_transaction_id =
if let Some(network_transaction_id) = pm_resp_network_transaction_id {
- let profile_id = payment_data
- .payment_intent
- .profile_id
- .as_ref()
- .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
-
- let pg_agnostic = state
- .store
- .find_config_by_key_unwrap_or(
- &format!("pg_agnostic_mandate_{}", profile_id),
- Some("false".to_string()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("The pg_agnostic config was not found in the DB")?;
-
- if &pg_agnostic.config == "true"
+ if is_connector_agnostic_mit_enabled == Some(true)
&& payment_data.payment_intent.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
{
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 304e6edd62e..958c3f4362f 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -64,8 +64,8 @@ pub async fn save_payment_method<FData>(
key_store: &domain::MerchantKeyStore,
amount: Option<i64>,
currency: Option<storage_enums::Currency>,
- profile_id: Option<String>,
billing_name: Option<masking::Secret<String>>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
where
FData: mandate::MandateBehaviour + Clone,
@@ -91,21 +91,7 @@ where
let network_transaction_id =
if let Some(network_transaction_id) = network_transaction_id {
- let profile_id = profile_id
- .as_ref()
- .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
-
- let pg_agnostic = state
- .store
- .find_config_by_key_unwrap_or(
- &format!("pg_agnostic_mandate_{}", profile_id),
- Some("false".to_string()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("The pg_agnostic config was not found in the DB")?;
-
- if &pg_agnostic.config == "true"
+ if business_profile.is_connector_agnostic_mit_enabled == Some(true)
&& save_payment_method_data.request.get_setup_future_usage()
== Some(storage_enums::FutureUsage::OffSession)
{
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index bec90c51e9c..31825617398 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -9,6 +9,7 @@ use api_models::{
};
#[cfg(not(feature = "business_profile_routing"))]
use common_utils::ext_traits::{Encode, StringExt};
+#[cfg(not(feature = "business_profile_routing"))]
use diesel_models::configs;
#[cfg(feature = "business_profile_routing")]
use diesel_models::routing_algorithm::RoutingAlgorithm;
@@ -806,37 +807,6 @@ pub async fn retrieve_linked_routing_config(
}
}
-pub async fn upsert_connector_agnostic_mandate_config(
- state: AppState,
- business_profile_id: &str,
- mandate_config: routing_types::DetailedConnectorChoice,
-) -> RouterResponse<routing_types::DetailedConnectorChoice> {
- let key = helpers::get_pg_agnostic_mandate_config_key(business_profile_id);
-
- let mandate_config_str = mandate_config.enabled.to_string();
-
- let find_config = state
- .store
- .find_config_by_key_unwrap_or(&key, Some(mandate_config_str.clone()))
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error saving pg agnostic mandate config to db")?;
-
- if find_config.config != mandate_config_str {
- let config_update = configs::ConfigUpdate::Update {
- config: Some(mandate_config_str),
- };
- state
- .store
- .update_config_by_key(&key, config_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error saving pg agnostic mandate config to db")?;
- }
-
- Ok(service_api::ApplicationResponse::Json(mandate_config))
-}
-
pub async fn retrieve_default_routing_config_for_profiles(
state: AppState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index fb86ba5a87b..3702498767a 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -272,47 +272,6 @@ pub async fn update_business_profile_active_algorithm_ref(
Ok(())
}
-pub async fn get_merchant_connector_agnostic_mandate_config(
- db: &dyn StorageInterface,
- business_profile_id: &str,
-) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> {
- let key = get_pg_agnostic_mandate_config_key(business_profile_id);
- let maybe_config = db.find_config_by_key(&key).await;
-
- match maybe_config {
- Ok(config) => config
- .config
- .parse_struct("Vec<DetailedConnectorChoice>")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("pg agnostic mandate config has invalid structure"),
-
- Err(e) if e.current_context().is_db_not_found() => {
- let new_mandate_config: Vec<routing_types::DetailedConnectorChoice> = Vec::new();
-
- let serialized = new_mandate_config
- .encode_to_string_of_json()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error serializing newly created pg agnostic mandate config")?;
-
- let new_config = configs::ConfigNew {
- key,
- config: serialized,
- };
-
- db.insert_config(new_config)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error inserting new pg agnostic mandate config in db")?;
-
- Ok(new_mandate_config)
- }
-
- Err(e) => Err(e)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error fetching pg agnostic mandate config for merchant from db"),
- }
-}
-
pub async fn validate_connectors_in_routing_config(
db: &dyn StorageInterface,
key_store: &domain::MerchantKeyStore,
@@ -441,12 +400,6 @@ pub fn get_routing_dictionary_key(merchant_id: &str) -> String {
format!("routing_dict_{merchant_id}")
}
-/// Provides the identifier for the specific merchant's agnostic_mandate_config
-#[inline(always)]
-pub fn get_pg_agnostic_mandate_config_key(business_profile_id: &str) -> String {
- format!("pg_agnostic_mandate_{business_profile_id}")
-}
-
/// Provides the identifier for the specific merchant's default_config
#[inline(always)]
pub fn get_default_config_key(
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 6a8a4ee5e03..0ee44429756 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -466,10 +466,6 @@ impl Routing {
)
})),
)
- .service(
- web::resource("/business_profile/{business_profile_id}/configs/pg_agnostic_mit")
- .route(web::post().to(cloud_routing::upsert_connector_agnostic_mandate_config)),
- )
.service(
web::resource("/default")
.route(web::get().to(|state, req| {
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index bf91f8055d1..1e301b069ae 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -231,7 +231,6 @@ impl From<Flow> for ApiIdentifier {
| Flow::ReconTokenRequest
| Flow::ReconServiceRequest
| Flow::ReconVerifyToken => Self::Recon,
- Flow::CreateConnectorAgnosticMandateConfig => Self::Routing,
Flow::RetrievePollStatus => Self::Poll,
}
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 8438424546c..556e91d8694 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -566,41 +566,6 @@ pub async fn routing_retrieve_linked_config(
}
}
-#[cfg(feature = "olap")]
-#[instrument(skip_all)]
-pub async fn upsert_connector_agnostic_mandate_config(
- state: web::Data<AppState>,
- req: HttpRequest,
- json_payload: web::Json<routing_types::DetailedConnectorChoice>,
- path: web::Path<String>,
-) -> impl Responder {
- use crate::services::authentication::AuthenticationData;
-
- let flow = Flow::CreateConnectorAgnosticMandateConfig;
- let business_profile_id = path.into_inner();
-
- Box::pin(oss_api::server_wrap(
- flow,
- state,
- &req,
- json_payload.into_inner(),
- |state, _auth: AuthenticationData, mandate_config, _| {
- Box::pin(routing::upsert_connector_agnostic_mandate_config(
- state,
- &business_profile_id,
- mandate_config,
- ))
- },
- auth::auth_type(
- &auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::RoutingWrite),
- req.headers(),
- ),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn routing_retrieve_default_config_for_profiles(
diff --git a/crates/router/src/types/api/routing.rs b/crates/router/src/types/api/routing.rs
index faafac76e3d..4f982d543df 100644
--- a/crates/router/src/types/api/routing.rs
+++ b/crates/router/src/types/api/routing.rs
@@ -3,9 +3,9 @@ pub use api_models::routing::RoutableChoiceKind;
pub use api_models::{
enums as api_enums,
routing::{
- ConnectorVolumeSplit, DetailedConnectorChoice, RoutableConnectorChoice, RoutingAlgorithm,
- RoutingAlgorithmKind, RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary,
- RoutingDictionaryRecord, StraightThroughAlgorithm,
+ ConnectorVolumeSplit, RoutableConnectorChoice, RoutingAlgorithm, RoutingAlgorithmKind,
+ RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord,
+ StraightThroughAlgorithm,
},
};
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index e8ffe0685b2..14b235eadb2 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -210,8 +210,6 @@ pub enum Flow {
RoutingRetrieveConfig,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
- /// Update connector agnostic mandate config
- CreateConnectorAgnosticMandateConfig,
/// Routing retrieve default config
RoutingRetrieveDefaultConfig,
/// Routing retrieve dictionary
|
2024-04-29T10:54:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Remove the `configs/pg_agnostic_mit` api as there is a new api added to enabled the same feature in this [pr](https://github.com/juspay/hyperswitch/pull/4480). Also this pr includes changes to read the `is_connector_agnostic_mit` flow form the business profile.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1) Creata Merchant account
2) Enable the `connector_agnostic_mit` flow for the `profile_id`
```
curl --location 'http://localhost:8080/account/:merchant_id/business_profile/:profile_id/toggle_connector_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api_key' \
--data '{
"enabled": true
}'
```
3) Create MCA for stripe and cybersource
4) Create a initial mandate with stripe
```
{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cyb111",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"metadata": {
"frequency": "1"
}
,
"end_date": "2025-05-03T04:07:52.723Z"
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
<img width="1183" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/846d10a2-b558-4107-ae76-28e7f64eda09">
5) Copy the `payment_method_id` form the intial mandate response and do the `mit` by passing the routing connector as cybersource
```
{
"amount": 499,
"currency": "USD",
"confirm": true,
"profile_id": "pro_PUqIPYItrChfHMWQTijY",
"capture_method": "automatic",
"customer_id": "cyb111",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_JwKhxZ1l5Beoh3tiU38f"
},
"routing": {
"type": "single",
"data": {
"connector": "cybersource",
"merchant_connector_id": "mca_1AaY3OI8lL1gLv2ekaTd"
}
},
"payment_method": "card",
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}
```
<img width="1164" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/b0da9f2a-8bbc-4125-a207-3cda3a9ff641">
## Checklist
<!-- Put an `x` in 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
|
f63a97024c755fd30a3403e2146812fe4edb8067
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4483
|
Bug: extended_card_info API to retrieve encrypted card PAN
New endpoint to retrieve the extended card info from redis given payment_id and api_key as auth
|
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index b8f4a9d6d90..59e65c0605f 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -8,9 +8,10 @@ use crate::{
PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
- PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters,
- PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest,
- PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
+ ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints,
+ PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2,
+ PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest,
+ PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest,
PaymentsStartRequest, RedirectionResponse,
@@ -201,3 +202,5 @@ impl ApiEventMetric for PaymentsExternalAuthenticationRequest {
})
}
}
+
+impl ApiEventMetric for ExtendedCardInfoResponse {}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5d35ba3e490..bd19443d002 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4622,6 +4622,12 @@ pub enum PaymentLinkStatusWrap {
IntentStatus(api_enums::IntentStatus),
}
+#[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct ExtendedCardInfoResponse {
+ // Encrypted customer payment method data
+ pub payload: String,
+}
+
#[cfg(test)]
mod payments_request_api_contract {
#![allow(clippy::unwrap_used)]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index bb9ef731992..810143d115b 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -470,6 +470,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
+ api_models::payments::ExtendedCardInfoResponse,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 580eb4a80bc..bca1cbb64b8 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -262,6 +262,8 @@ pub enum StripeErrorCode {
CurrencyConversionFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")]
+ ExtendedCardInfoNotFound,
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
@@ -643,6 +645,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => {
Self::InvalidWalletToken { wallet_name }
}
+ errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound,
}
}
}
@@ -714,7 +717,8 @@ impl actix_web::ResponseError for StripeErrorCode {
| Self::PaymentMethodUnactivated
| Self::InvalidConnectorConfiguration { .. }
| Self::CurrencyConversionFailed
- | Self::PaymentMethodDeleteFailed => StatusCode::BAD_REQUEST,
+ | Self::PaymentMethodDeleteFailed
+ | Self::ExtendedCardInfoNotFound => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::PayoutFailed
| Self::PaymentLinkNotFound
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index 5d1e527d6d4..0c492f0f089 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -269,6 +269,8 @@ pub enum ApiErrorResponse {
message = "Invalid Cookie"
)]
InvalidCookie,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
+ ExtendedCardInfoNotFound,
}
impl PTError for ApiErrorResponse {
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index 1197e01cdf4..880c0d7b20b 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -301,6 +301,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::InvalidCookie => {
AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
}
+ Self::ExtendedCardInfoNotFound => {
+ AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
+ }
}
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 67f095450c0..3f775397b19 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3992,3 +3992,26 @@ pub async fn payment_external_authentication(
},
))
}
+
+#[instrument(skip_all)]
+pub async fn get_extended_card_info(
+ state: AppState,
+ merchant_id: String,
+ payment_id: String,
+) -> RouterResponse<payments_api::ExtendedCardInfoResponse> {
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let key = helpers::get_redis_key_for_extended_card_info(&merchant_id, &payment_id);
+ let payload = redis_conn
+ .get_key::<String>(&key)
+ .await
+ .change_context(errors::ApiErrorResponse::ExtendedCardInfoNotFound)?;
+
+ Ok(services::ApplicationResponse::Json(
+ payments_api::ExtendedCardInfoResponse { payload },
+ ))
+}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6a1a779fd1f..c82f73e2f7b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4320,3 +4320,7 @@ pub fn validate_mandate_data_and_future_usage(
Ok(())
}
}
+
+pub fn get_redis_key_for_extended_card_info(merchant_id: &str, payment_id: &str) -> String {
+ format!("{merchant_id}_{payment_id}_extended_card_info")
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index a7c6f1486d3..1e9df096279 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -382,6 +382,9 @@ impl Payments {
)
.service(
web::resource("/{payment_id}/3ds/authentication").route(web::post().to(payments_external_authentication)),
+ )
+ .service(
+ web::resource("/{payment_id}/extended_card_info").route(web::get().to(retrieve_extended_card_info)),
);
}
route
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index c7b1b28f2eb..8bfbd0ad0f6 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -120,7 +120,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsRedirect
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExternalAuthentication
- | Flow::PaymentsAuthorize => Self::Payments,
+ | Flow::PaymentsAuthorize
+ | Flow::GetExtendedCardInfo => Self::Payments,
Flow::PayoutsCreate
| Flow::PayoutsRetrieve
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index c1d67c4ce00..c9e1cf14ce3 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1357,6 +1357,30 @@ pub async fn post_3ds_payments_authorize(
.await
}
+/// Retrieve endpoint for merchant to fetch the encrypted customer payment method data
+#[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))]
+pub async fn retrieve_extended_card_info(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ path: web::Path<String>,
+) -> impl Responder {
+ let flow = Flow::GetExtendedCardInfo;
+ let payment_id = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payment_id,
+ |state, auth, payment_id, _| {
+ payments::get_extended_card_info(state, auth.merchant_account.merchant_id, payment_id)
+ },
+ &auth::ApiKeyAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub fn get_or_generate_payment_id(
payload: &mut payment_types::PaymentsRequest,
) -> errors::RouterResult<()> {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 705596abe84..719fa84a999 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -408,6 +408,8 @@ pub enum Flow {
RetrievePollStatus,
/// Toggles the extended card info feature in profile level
ToggleExtendedCardInfo,
+ /// Get the extended card info associated to a payment_id
+ GetExtendedCardInfo,
}
///
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index bb8945c530a..d0addf07c98 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -8707,6 +8707,17 @@
"mandate_revoked"
]
},
+ "ExtendedCardInfoResponse": {
+ "type": "object",
+ "required": [
+ "payload"
+ ],
+ "properties": {
+ "payload": {
+ "type": "string"
+ }
+ }
+ },
"ExternalAuthenticationDetailsResponse": {
"type": "object",
"required": [
|
2024-04-29T09:54:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds a new endpoint to retrieve the extended card info (encrypted) stored in redis under a given merchant and payment.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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)?
-->
This PR cannot be tested until https://github.com/juspay/hyperswitch/issues/4482 goes in.
For local testing I manually set redis entry and tried to hit this newly added endpoint.
1. Create merchant account and api key
2. Create a payment
3. Got the payment id and merchant id and set the redis entry
```
set merchant_1713971568_pay_1nrIoi2hRnzsy1V2cEv6_extended_card_info "eyJlbmMiOiJBMjU2R0NNIiwidHlwIjoiSldUIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.sTmCdgRVEz4hZKZ5VxQxq4Dt_V6v9O_96dIXy5F6lzdePOVQ2CwYJQeMhrsFjfk8kZrdOsfeOfFV1FVmxhWjREUvVBZKld5p47HDi4GAEDCX10HH9hIE3SD-IfU4D9riyE2MpIiWoB6xMVNxOvZSWAh2r_-UBgMzAoTAvz7ecmFJopRa8691up8H-Bc7DsVUxfAnEPef9bUIXd2Ej8vWR_XNyx9giPPwhYqYwtcsyyBnpnkyJW26Cc0J-zgbkT-6SPzTfpt_ALUons8nj3uQkmurpaQGdbBj9Zb_BOjK7ytngohnr68Z6ftb0-K41XYMrl11v1Rb-S_enQBstMsyVA.kh4VJ86tKDm5mwh9.WzF74jEuhZMQrYvNgl3e8Ll8YVMXwOizKdgbdBF0i6VWywXKPCIlwD150gtKo15u1_Xvo-151jTAp56E1w3vT2vOUyXWf96MTFytZR3VE4ClLB27AIu_4oUPJ5iG9IVLcMsUxEp4-OM0kNtrpbUY-Fyb3COwZ5AtZ2Fhx_CSiUp1ZdyvoP7XEfkwWgSGU2qW1s9P5VxsaKyFtva7nPo2trJw8-805P3Qtdm-27XvFYNKcTRYUJ9XBDn-cinbo-qrqe2XFQ5lh7fClhHK2H_hiJdk_WBq4iZKBK-XJpeDjCCNtiAVDGw.e2duyijt4Py7nmU-1PygSg"
```
4. Hit the endpoint to retrieve the payload
```
curl --location 'http://localhost:8080/payments/pay_1nrIoi2hRnzsy1V2cEv6/extended_card_info' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_KM55eCA115eJaTBYK6Z8DYLwI6EghXzZDUb9M1RzE6Ji1jMEhs71C8c43ndOubXw' \
--data ''
```

5. If another merchant tries to retrieve the same payload by passing same payment_id, throw 404

## Checklist
<!-- Put an `x` in 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
|
3077a0d31e8d36f18e359f1edf9a742969601f6b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4488
|
Bug: [REFACTOR]: Remove payment_method_id from RouterData struct
### Feature Description
This will remove the unused payment_method_id field from the Router_data, which is not at all used anywhere in our codebase, as we are storing the pm_id in payment_attempt.
### Possible Implementation
Removal of `payment_method_id` from the `RouterData` struct as whole and same for all the references of the struct.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index abefd12c77d..d4cad2fbedb 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -168,7 +168,6 @@ pub fn construct_router_data<F: Clone, Req, Res>(
connector_api_version: None,
request: request_data,
response: Err(types::ErrorResponse::default()),
- payment_method_id: None,
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(),
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index f17a1730088..58e82ec21c7 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -63,7 +63,6 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
connector_auth_type: auth_type,
description: None,
return_url: None,
- payment_method_id: None,
payment_method_status: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index a76408b5d3d..50ebea24878 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -71,7 +71,6 @@ pub async fn construct_fulfillment_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: payment_intent.return_url.clone(),
- payment_method_id: payment_attempt.payment_method_id.clone(),
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index cba19769d57..ad74f7f7027 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -62,7 +62,6 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
connector_auth_type: auth_type,
description: None,
return_url: None,
- payment_method_id: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index c9f5e4dac0a..0ce0c89bd35 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -58,7 +58,6 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
connector_auth_type: auth_type,
description: None,
return_url: None,
- payment_method_id: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index dc385093f23..5634916b212 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -69,7 +69,6 @@ impl
connector_auth_type: auth_type,
description: None,
return_url: None,
- payment_method_id: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index 7b4933812e5..ec438ee6d78 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -59,7 +59,6 @@ pub async fn construct_mandate_revoke_router_data(
connector_mandate_id: mandate.connector_mandate_id,
},
response: Err(types::ErrorResponse::get_not_implemented()),
- payment_method_id: None,
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW.to_string(),
test_mode: None,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6a1a779fd1f..bcc911e497a 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3244,7 +3244,6 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
description: router_data.description,
payment_id: router_data.payment_id,
payment_method: router_data.payment_method,
- payment_method_id: router_data.payment_method_id,
return_url: router_data.return_url,
status: router_data.status,
attempt_id: router_data.attempt_id,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 4580181d394..47d659b5ed2 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -966,7 +966,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
status: updated_attempt_status,
connector: None,
connector_transaction_id,
- payment_method_id: router_data.payment_method_id,
+ payment_method_id: payment_data
+ .payment_attempt
+ .payment_method_id
+ .clone(),
error_code: Some(reason.clone().map(|cd| cd.code)),
error_message: Some(reason.clone().map(|cd| cd.message)),
error_reason: Some(reason.map(|cd| cd.message)),
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 71cded04e1a..58c58ffaef8 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -384,7 +384,7 @@ where
.connector_response_reference_id
.clone(),
authentication_type: None,
- payment_method_id: router_data.payment_method_id,
+ payment_method_id: payment_data.payment_attempt.payment_method_id.clone(),
mandate_id: payment_data
.mandate_id
.clone()
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index eba5768a9ce..b891998dae3 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -141,7 +141,6 @@ where
connector_auth_type: auth_type,
description: payment_data.payment_intent.description.clone(),
return_url: payment_data.payment_intent.return_url.clone(),
- payment_method_id: payment_data.payment_attempt.payment_method_id.clone(),
address: payment_data
.address
.unify_with_payment_method_data_billing(payment_method_data_billing),
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index c67aafe938f..c7a22e56897 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -160,7 +160,6 @@ pub async fn construct_payout_router_data<'a, F>(
connector_auth_type,
description: None,
return_url: payouts.return_url.to_owned(),
- payment_method_id: None,
address,
auth_type: enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata(),
@@ -311,7 +310,6 @@ pub async fn construct_refund_router_data<'a, F>(
connector_auth_type: auth_type,
description: None,
return_url: payment_intent.return_url.clone(),
- payment_method_id: payment_attempt.payment_method_id.clone(),
// Does refund need shipping/billing address ?
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
@@ -557,7 +555,6 @@ pub async fn construct_accept_dispute_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: payment_intent.return_url.clone(),
- payment_method_id: payment_attempt.payment_method_id.clone(),
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
@@ -652,7 +649,6 @@ pub async fn construct_submit_evidence_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: payment_intent.return_url.clone(),
- payment_method_id: payment_attempt.payment_method_id.clone(),
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
@@ -745,7 +741,6 @@ pub async fn construct_upload_file_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: payment_intent.return_url.clone(),
- payment_method_id: payment_attempt.payment_method_id.clone(),
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
@@ -842,7 +837,6 @@ pub async fn construct_defend_dispute_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: payment_intent.return_url.clone(),
- payment_method_id: payment_attempt.payment_method_id.clone(),
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
@@ -930,7 +924,6 @@ pub async fn construct_retrieve_file_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: None,
- payment_method_id: None,
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata(),
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 739d7b20fdd..3bf8c7c7f21 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -83,7 +83,6 @@ pub async fn construct_webhook_router_data<'a>(
connector_auth_type: auth_type,
description: None,
return_url: None,
- payment_method_id: None,
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 639efe3f069..77d53584dab 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -303,9 +303,6 @@ pub struct RouterData<Flow, Request, Response> {
/// Contains flow-specific data that the connector responds with.
pub response: Result<Response, ErrorResponse>,
- /// Contains any error response that the connector returns.
- pub payment_method_id: Option<String>,
-
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
@@ -1541,7 +1538,6 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)>
amount_captured: data.amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
- payment_method_id: data.payment_method_id.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
@@ -1602,7 +1598,6 @@ impl<F1, F2>
amount_captured: data.amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
- payment_method_id: data.payment_method_id.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 55dc4a2bf04..39891a7075d 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -81,7 +81,6 @@ impl VerifyConnectorData {
payment_method: storage_enums::PaymentMethod::Card,
amount_captured: None,
preprocessing_id: None,
- payment_method_id: None,
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 4da849c4e2a..710d90a4ea3 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -33,7 +33,6 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
description: Some("This is a test".to_string()),
return_url: None,
payment_method_status: None,
- payment_method_id: None,
request: types::PaymentsAuthorizeData {
amount: 1000,
currency: enums::Currency::USD,
@@ -133,7 +132,6 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
connector: "aci".to_string(),
payment_id: uuid::Uuid::new_v4().to_string(),
attempt_id: uuid::Uuid::new_v4().to_string(),
- payment_method_id: None,
payment_method_status: None,
status: enums::AttemptStatus::default(),
payment_method: enums::PaymentMethod::Card,
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index fd472aa9411..9678eca73f3 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -503,7 +503,6 @@ pub trait ConnectorActions: Connector {
payment_id: uuid::Uuid::new_v4().to_string(),
attempt_id: uuid::Uuid::new_v4().to_string(),
status: enums::AttemptStatus::default(),
- payment_method_id: None,
auth_type: info
.clone()
.map_or(enums::AuthenticationType::NoThreeDs, |a| {
|
2024-04-29T10:16:53Z
|
## 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 will remove the unused `payment_method_id` field from the Router_data, which is not at all used anywhere in our codebase, as we are storing the pm_id in `payment_attempt`.
### 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).
-->
Code Refactoring
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Payment_Method_flows seems working (AE).
## Checklist
<!-- Put an `x` in 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
|
ac9d856add0220701f809c8eb0668afe77003ef7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4482
|
Bug: Store encrypted raw card info in redis
While the customer is making a payment, we’ll check whether the extended card info feature is enabled through profile_id in the business profile. If enabled, we’ll fetch the merchant public_key and ttl from config. We’ll encrypt the card using the public key and store it in redis until ttl with the key being `{merchant_id}_{payment_id}_extended_card_info`.
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index d4d1b3d80b9..fde693a3700 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use common_utils::{
+ consts,
crypto::{Encryptable, OptionalEncryptableName},
pii,
};
@@ -1099,8 +1100,47 @@ pub struct ExtendedCardInfoChoice {
impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {}
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ExtendedCardInfoConfig {
+ /// Merchant public key
+ #[schema(value_type = String)]
pub public_key: Secret<String>,
- pub ttl_in_secs: u16,
+ /// TTL for extended card info
+ #[schema(default = 900, maximum = 3600, value_type = u16)]
+ #[serde(default)]
+ pub ttl_in_secs: TtlForExtendedCardInfo,
+}
+
+#[derive(Debug, serde::Serialize, Clone)]
+pub struct TtlForExtendedCardInfo(u16);
+
+impl Default for TtlForExtendedCardInfo {
+ fn default() -> Self {
+ Self(consts::DEFAULT_TTL_FOR_EXTENDED_CARD_INFO)
+ }
+}
+
+impl<'de> Deserialize<'de> for TtlForExtendedCardInfo {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let value = u16::deserialize(deserializer)?;
+
+ // Check if value exceeds the maximum allowed
+ if value > consts::MAX_TTL_FOR_EXTENDED_CARD_INFO {
+ Err(serde::de::Error::custom(
+ "ttl_in_secs must be less than or equal to 3600 (1hr)",
+ ))
+ } else {
+ Ok(Self(value))
+ }
+ }
+}
+
+impl std::ops::Deref for TtlForExtendedCardInfo {
+ type Target = u16;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index d730fa8c859..3385b633699 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -916,6 +916,58 @@ pub struct Card {
pub nick_name: Option<Secret<String>>,
}
+#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct ExtendedCardInfo {
+ /// The card number
+ #[schema(value_type = String, example = "4242424242424242")]
+ pub card_number: CardNumber,
+
+ /// The card's expiry month
+ #[schema(value_type = String, example = "24")]
+ pub card_exp_month: Secret<String>,
+
+ /// The card's expiry year
+ #[schema(value_type = String, example = "24")]
+ pub card_exp_year: Secret<String>,
+
+ /// The card holder's name
+ #[schema(value_type = String, example = "John Test")]
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The name of the issuer of card
+ #[schema(example = "chase")]
+ pub card_issuer: Option<String>,
+
+ /// The card network for the card
+ #[schema(value_type = Option<CardNetwork>, example = "Visa")]
+ pub card_network: Option<api_enums::CardNetwork>,
+
+ #[schema(example = "CREDIT")]
+ pub card_type: Option<String>,
+
+ #[schema(example = "INDIA")]
+ pub card_issuing_country: Option<String>,
+
+ #[schema(example = "JP_AMEX")]
+ pub bank_code: Option<String>,
+}
+
+impl From<Card> for ExtendedCardInfo {
+ fn from(value: Card) -> Self {
+ Self {
+ card_number: value.card_number,
+ card_exp_month: value.card_exp_month,
+ card_exp_year: value.card_exp_year,
+ card_holder_name: value.card_holder_name,
+ card_issuer: value.card_issuer,
+ card_network: value.card_network,
+ card_type: value.card_type,
+ card_issuing_country: value.card_issuing_country,
+ bank_code: value.bank_code,
+ }
+ }
+}
+
impl GetAddressFromPaymentMethodData for Card {
fn get_billing_address(&self) -> Option<Address> {
// Create billing address if first_name is some or if it is not ""
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index d9d1f18c347..509056152eb 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -77,3 +77,9 @@ pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false;
/// Default bool to enable saved payment method
pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false;
+
+/// Default ttl for Extended card info in redis (in seconds)
+pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60;
+
+/// Max ttl for Extended card info in redis (in seconds)
+pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60;
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 810143d115b..d701b64adbf 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -194,6 +194,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::AuthenticationConnectorDetails,
+ api_models::admin::ExtendedCardInfoConfig,
api_models::customers::CustomerRequest,
api_models::customers::CustomerDeleteResponse,
api_models::payment_methods::PaymentMethodCreate,
@@ -407,6 +408,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::ThreeDsMethodData,
api_models::payments::PollConfigResponse,
api_models::payments::ExternalAuthenticationDetailsResponse,
+ api_models::payments::ExtendedCardInfo,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e2a5f148440..895e5157c00 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -527,6 +527,16 @@ where
let cloned_payment_data = payment_data.clone();
let cloned_customer = customer.clone();
+ operation
+ .to_domain()?
+ .store_extended_card_info_temporarily(
+ state,
+ &payment_data.payment_intent.payment_id,
+ &business_profile,
+ &payment_data.payment_method_data,
+ )
+ .await?;
+
crate::utils::trigger_payments_webhook(
merchant_account,
business_profile,
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index d4590782b0a..c214decb0b4 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -190,6 +190,16 @@ pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
+
+ async fn store_extended_card_info_temporarily<'a>(
+ &'a self,
+ _state: &AppState,
+ _payment_id: &str,
+ _business_profile: &storage::BusinessProfile,
+ _payment_method_data: &Option<api::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse> {
+ Ok(())
+ }
}
#[async_trait]
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 72e0903f7c3..79680cb80cc 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1,10 +1,11 @@
use std::marker::PhantomData;
-use api_models::enums::FrmSuggestion;
+use api_models::{admin::ExtendedCardInfoConfig, enums::FrmSuggestion, payments::ExtendedCardInfo};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use error_stack::{report, ResultExt};
use futures::FutureExt;
+use masking::{ExposeInterface, PeekInterface};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use tracing_futures::Instrument;
@@ -895,6 +896,70 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
) -> CustomResult<bool, errors::ApiErrorResponse> {
blocklist_utils::validate_data_for_blocklist(state, merchant_account, payment_data).await
}
+
+ #[instrument(skip_all)]
+ async fn store_extended_card_info_temporarily<'a>(
+ &'a self,
+ state: &AppState,
+ payment_id: &str,
+ business_profile: &storage::BusinessProfile,
+ payment_method_data: &Option<api::PaymentMethodData>,
+ ) -> CustomResult<(), errors::ApiErrorResponse> {
+ if let (Some(true), Some(api::PaymentMethodData::Card(card)), Some(merchant_config)) = (
+ business_profile.is_extended_card_info_enabled,
+ payment_method_data,
+ business_profile.extended_card_info_config.clone(),
+ ) {
+ let merchant_config = merchant_config
+ .expose()
+ .parse_value::<ExtendedCardInfoConfig>("ExtendedCardInfoConfig")
+ .map_err(|err| logger::error!(parse_err=?err,"Error while parsing ExtendedCardInfoConfig"));
+
+ let card_data = ExtendedCardInfo::from(card.clone())
+ .encode_to_vec()
+ .map_err(|err| logger::error!(encode_err=?err,"Error while encoding ExtendedCardInfo to vec"));
+
+ let (Ok(merchant_config), Ok(card_data)) = (merchant_config, card_data) else {
+ return Ok(());
+ };
+
+ let encrypted_payload =
+ services::encrypt_jwe(&card_data, merchant_config.public_key.peek())
+ .await
+ .map_err(|err| {
+ logger::error!(jwe_encryption_err=?err,"Error while JWE encrypting extended card info")
+ });
+
+ let Ok(encrypted_payload) = encrypted_payload else {
+ return Ok(());
+ };
+
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let key = helpers::get_redis_key_for_extended_card_info(
+ &business_profile.merchant_id,
+ payment_id,
+ );
+
+ redis_conn
+ .set_key_with_expiry(
+ &key,
+ encrypted_payload.clone(),
+ (*merchant_config.ttl_in_secs).into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add extended card info in redis")?;
+
+ logger::info!("Extended card info added to redis");
+ }
+
+ Ok(())
+ }
}
#[async_trait]
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 9d9d96ccac1..18ba4c6b99e 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -8707,6 +8707,86 @@
"mandate_revoked"
]
},
+ "ExtendedCardInfo": {
+ "type": "object",
+ "required": [
+ "card_number",
+ "card_exp_month",
+ "card_exp_year",
+ "card_holder_name"
+ ],
+ "properties": {
+ "card_number": {
+ "type": "string",
+ "description": "The card number",
+ "example": "4242424242424242"
+ },
+ "card_exp_month": {
+ "type": "string",
+ "description": "The card's expiry month",
+ "example": "24"
+ },
+ "card_exp_year": {
+ "type": "string",
+ "description": "The card's expiry year",
+ "example": "24"
+ },
+ "card_holder_name": {
+ "type": "string",
+ "description": "The card holder's name",
+ "example": "John Test"
+ },
+ "card_issuer": {
+ "type": "string",
+ "description": "The name of the issuer of card",
+ "example": "chase",
+ "nullable": true
+ },
+ "card_network": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardNetwork"
+ }
+ ],
+ "nullable": true
+ },
+ "card_type": {
+ "type": "string",
+ "example": "CREDIT",
+ "nullable": true
+ },
+ "card_issuing_country": {
+ "type": "string",
+ "example": "INDIA",
+ "nullable": true
+ },
+ "bank_code": {
+ "type": "string",
+ "example": "JP_AMEX",
+ "nullable": true
+ }
+ }
+ },
+ "ExtendedCardInfoConfig": {
+ "type": "object",
+ "required": [
+ "public_key"
+ ],
+ "properties": {
+ "public_key": {
+ "type": "string",
+ "description": "Merchant public key"
+ },
+ "ttl_in_secs": {
+ "type": "integer",
+ "format": "int32",
+ "description": "TTL for extended card info",
+ "default": 900,
+ "maximum": 3600,
+ "minimum": 0
+ }
+ }
+ },
"ExtendedCardInfoResponse": {
"type": "object",
"required": [
|
2024-04-29T13:04:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
While the customer is making a payment, we’ll check whether the extended card info feature is enabled through `profile_id` in the business profile. If enabled, we’ll fetch the merchant `public_key` and `ttl` from config. We’ll encrypt the card using the public key and store it in redis until ttl with the key being `{merchant_id}_{payment_id}_extended_card_info`.
This PR also makes the `ttl` field as an optional field. the default value would be 15 min (900 seconds) and max value would be 1 hr (3600 seconds).
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Create merchant account (get default profile_id)
2. Create api key
3. Create mca (any connector)
4. Enable extended card info feature
```
curl --location 'http://localhost:8080/account/:merchant_id/business_profile/:profile_id/toggle_extended_card_info' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"enabled": true
}'
```

5. Use update endpoint of business profile to pass config.
```
curl --location 'http://localhost:8080/account/:merchant_id/business_profile/:profile_id' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"extended_card_info_config": {
"public_key": "pub_key_1",
"ttl_in_secs": 60
}
}'
```

6. Create a normal card payment.
7. Hit the endpoint to retrieve the payload (PR - https://github.com/juspay/hyperswitch/pull/4484)
```
curl --location 'http://localhost:8080/payments/pay_1nrIoi2hRnzsy1V2cEv6/extended_card_info' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_KM55eCA115eJaTBYK6Z8DYLwI6EghXzZDUb9M1RzE6Ji1jMEhs71C8c43ndOubXw' \
--data ''
```

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4f4cbdff21b956b5939cdbe6a4f88f663e6b1281
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4479
|
Bug: Add an api to toggle `connector_agnostic_mit` feature
Add api to toggle `connector_agnostic_mit` to enable usage of Network Transaction/Reference ID in recurring mandate payments. This will be a business profile level feature that a merchant specifies.
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index fde693a3700..75bd2a31d8e 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1100,6 +1100,13 @@ pub struct ExtendedCardInfoChoice {
impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
+pub struct ConnectorAgnosticMitChoice {
+ pub enabled: bool,
+}
+
+impl common_utils::events::ApiEventMetric for ConnectorAgnosticMitChoice {}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ExtendedCardInfoConfig {
/// Merchant public key
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 90a9dcbb7d8..1131e9ad674 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -37,6 +37,7 @@ pub struct BusinessProfile {
pub authentication_connector_details: Option<serde_json::Value>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -65,6 +66,7 @@ pub struct BusinessProfileNew {
pub authentication_connector_details: Option<serde_json::Value>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -90,6 +92,7 @@ pub struct BusinessProfileUpdateInternal {
pub authentication_connector_details: Option<serde_json::Value>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -117,6 +120,9 @@ pub enum BusinessProfileUpdate {
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
},
+ ConnectorAgnosticMitUpdate {
+ is_connector_agnostic_mit_enabled: Option<bool>,
+ },
}
impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
@@ -168,6 +174,12 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
is_extended_card_info_enabled,
..Default::default()
},
+ BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
+ is_connector_agnostic_mit_enabled,
+ } => Self {
+ is_connector_agnostic_mit_enabled,
+ ..Default::default()
+ },
}
}
}
@@ -195,6 +207,7 @@ impl From<BusinessProfileNew> for BusinessProfile {
payment_link_config: new.payment_link_config,
session_expiry: new.session_expiry,
authentication_connector_details: new.authentication_connector_details,
+ is_connector_agnostic_mit_enabled: new.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: new.is_extended_card_info_enabled,
extended_card_info_config: new.extended_card_info_config,
}
@@ -223,6 +236,7 @@ impl BusinessProfileUpdate {
authentication_connector_details,
is_extended_card_info_enabled,
extended_card_info_config,
+ is_connector_agnostic_mit_enabled,
} = self.into();
BusinessProfile {
profile_name: profile_name.unwrap_or(source.profile_name),
@@ -245,6 +259,7 @@ impl BusinessProfileUpdate {
session_expiry,
authentication_connector_details,
is_extended_card_info_enabled,
+ is_connector_agnostic_mit_enabled,
extended_card_info_config,
..source
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f5dc5abe1e6..2e28bc5d30f 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -194,6 +194,7 @@ diesel::table! {
authentication_connector_details -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
+ is_connector_agnostic_mit_enabled -> Nullable<Bool>,
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 7d2fabc3f37..0b8d52332d9 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1739,6 +1739,47 @@ pub async fn extended_card_info_toggle(
Ok(service_api::ApplicationResponse::Json(ext_card_info_choice))
}
+pub async fn connector_agnostic_mit_toggle(
+ state: AppState,
+ merchant_id: &str,
+ profile_id: &str,
+ connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice,
+) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> {
+ let db = state.store.as_ref();
+
+ let business_profile = db
+ .find_business_profile_by_profile_id(profile_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_string(),
+ })?;
+
+ if business_profile.merchant_id != merchant_id {
+ Err(errors::ApiErrorResponse::AccessForbidden {
+ resource: profile_id.to_string(),
+ })?
+ }
+
+ if business_profile.is_connector_agnostic_mit_enabled
+ != Some(connector_agnostic_mit_choice.enabled)
+ {
+ let business_profile_update =
+ storage::business_profile::BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
+ is_connector_agnostic_mit_enabled: Some(connector_agnostic_mit_choice.enabled),
+ };
+
+ db.update_business_profile_by_profile_id(business_profile, business_profile_update)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_owned(),
+ })?;
+ }
+
+ Ok(service_api::ApplicationResponse::Json(
+ connector_agnostic_mit_choice,
+ ))
+}
+
pub(crate) fn validate_auth_and_metadata_type(
connector_name: api_models::enums::Connector,
val: &types::ConnectorAuthType,
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 63d9f840a00..d9cadf002c1 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -589,6 +589,32 @@ pub async fn business_profiles_list(
)
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::ToggleConnectorAgnosticMit))]
+pub async fn toggle_connector_agnostic_mit(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<(String, String)>,
+ json_payload: web::Json<api_models::admin::ConnectorAgnosticMitChoice>,
+) -> HttpResponse {
+ let flow = Flow::ToggleConnectorAgnosticMit;
+ let (merchant_id, profile_id) = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, _, req, _| connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req),
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::RoutingWrite),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
/// Merchant Account - KV Status
///
/// Toggle KV mode for the Merchant Account
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 19a632bf895..c6b70ee5a9d 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1131,6 +1131,10 @@ impl BusinessProfile {
.service(
web::resource("/toggle_extended_card_info")
.route(web::post().to(toggle_extended_card_info)),
+ )
+ .service(
+ web::resource("/toggle_connector_agnostic_mit")
+ .route(web::post().to(toggle_connector_agnostic_mit)),
),
)
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index faef85f3901..69dbb8c0cfc 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -168,7 +168,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::BusinessProfileRetrieve
| Flow::BusinessProfileDelete
| Flow::BusinessProfileList
- | Flow::ToggleExtendedCardInfo => Self::Business,
+ | Flow::ToggleExtendedCardInfo
+ | Flow::ToggleConnectorAgnosticMit => Self::Business,
Flow::PaymentLinkRetrieve
| Flow::PaymentLinkInitiate
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 77fe8371817..793d042ea49 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -175,6 +175,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "authentication_connector_details",
})?,
+ is_connector_agnostic_mit_enabled: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
})
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 26cb619d74c..bfb297922fb 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -404,6 +404,8 @@ pub enum Flow {
RetrievePollStatus,
/// Toggles the extended card info feature in profile level
ToggleExtendedCardInfo,
+ /// Toggles the extended card info feature in profile level
+ ToggleConnectorAgnosticMit,
/// Get the extended card info associated to a payment_id
GetExtendedCardInfo,
}
diff --git a/migrations/2024-04-24-111807_add-is-connector_agnostic_mit/down.sql b/migrations/2024-04-24-111807_add-is-connector_agnostic_mit/down.sql
new file mode 100644
index 00000000000..80672e85a26
--- /dev/null
+++ b/migrations/2024-04-24-111807_add-is-connector_agnostic_mit/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE business_profile DROP COLUMN IF EXISTS is_connector_agnostic_mit_enabled;
\ No newline at end of file
diff --git a/migrations/2024-04-24-111807_add-is-connector_agnostic_mit/up.sql b/migrations/2024-04-24-111807_add-is-connector_agnostic_mit/up.sql
new file mode 100644
index 00000000000..beee3325617
--- /dev/null
+++ b/migrations/2024-04-24-111807_add-is-connector_agnostic_mit/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_connector_agnostic_mit_enabled BOOLEAN DEFAULT FALSE;
\ No newline at end of file
|
2024-04-29T07:19:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This pr adds a api to enable usage of Network Transaction/Reference ID in recurring MIT payments. This will be a business profile level feature that a merchant specifies.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1) Create a business profile for a merchant
2) Use the below curl to enable `connector_agnostic_mit` feature for the business profile
```
curl --location 'http://localhost:8080/account/:merchant_id/business_profile/:profile_id/toggle_connector_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api_key' \
--data '{
"enabled": true
}'
```
<img width="839" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67bcfaf9-ce19-435b-9846-8f74caea4310">

## Checklist
<!-- Put an `x` in 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
|
5442574c08fcce57bebad2cfbf6547a9b824da58
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4478
|
Bug: Include single purpose token and single purpose JWT auth
Create single purpose token and single purpose JWT auth that will server as generic for intermediate tokens and can be used for different cases, during TOTP, change passwords, accept invite etc.
|
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index c2a8669030b..2c4ec3f5e70 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -68,6 +68,8 @@ pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes
pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
+pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
+
pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token";
pub const USER_BLACKLIST_PREFIX: &str = "BU_";
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 5203b20c55b..9ac7e6dd3a3 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -64,6 +64,10 @@ pub enum AuthenticationType {
UserJwt {
user_id: String,
},
+ SinglePurposeJWT {
+ user_id: String,
+ purpose: Purpose,
+ },
MerchantId {
merchant_id: String,
},
@@ -101,11 +105,51 @@ impl AuthenticationType {
user_id: _,
}
| Self::WebhookAuth { merchant_id } => Some(merchant_id.as_ref()),
- Self::AdminApiKey | Self::UserJwt { .. } | Self::NoAuth => None,
+ Self::AdminApiKey
+ | Self::UserJwt { .. }
+ | Self::SinglePurposeJWT { .. }
+ | Self::NoAuth => None,
}
}
}
+#[derive(Clone, Debug)]
+pub struct UserFromSinglePurposeToken {
+ pub user_id: String,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct SinglePurposeToken {
+ pub user_id: String,
+ pub purpose: Purpose,
+ pub exp: u64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, strum::Display, serde::Deserialize, serde::Serialize)]
+pub enum Purpose {
+ AcceptInvite,
+}
+
+#[cfg(feature = "olap")]
+impl SinglePurposeToken {
+ pub async fn new_token(
+ user_id: String,
+ purpose: Purpose,
+ settings: &Settings,
+ ) -> UserResult<String> {
+ let exp_duration =
+ std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS);
+ let exp = jwt::generate_exp(exp_duration)?.as_secs();
+ let token_payload = Self {
+ user_id,
+ purpose,
+ exp,
+ };
+ jwt::generate_jwt(&token_payload, settings).await
+ }
+}
+
+// TODO: This has to be removed once single purpose token is used as a intermediate token
#[derive(Clone, Debug)]
pub struct UserWithoutMerchantFromToken {
pub user_id: String,
@@ -316,6 +360,42 @@ where
}
}
+#[allow(dead_code)]
+#[derive(Debug)]
+pub(crate) struct SinglePurposeJWTAuth(pub Purpose);
+
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<UserFromSinglePurposeToken, A> for SinglePurposeJWTAuth
+where
+ A: AppStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(UserFromSinglePurposeToken, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ if self.0 != payload.purpose {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ Ok((
+ UserFromSinglePurposeToken {
+ user_id: payload.user_id.clone(),
+ },
+ AuthenticationType::SinglePurposeJWT {
+ user_id: payload.user_id,
+ purpose: payload.purpose,
+ },
+ ))
+ }
+}
+
#[derive(Debug)]
pub struct AdminApiAuth;
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 7c1cbf27e10..b2f63f4927e 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -5,7 +5,7 @@ use common_utils::date_time;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
-use super::{AuthToken, UserAuthToken};
+use super::{AuthToken, SinglePurposeToken, UserAuthToken};
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
@@ -163,3 +163,13 @@ impl BlackList for UserAuthToken {
check_user_in_blacklist(state, &self.user_id, self.exp).await
}
}
+
+#[async_trait::async_trait]
+impl BlackList for SinglePurposeToken {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync,
+ {
+ check_user_in_blacklist(state, &self.user_id, self.exp).await
+ }
+}
|
2024-04-26T10:52:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add single purpose token and authentication for single purpose token. This token will serves as a intermediate token and used to perform a certain action only.
### 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 #4478
## How did you test it?
This can be tested with upcoming PRs for reset password, TOTP, accept invite etc. Single purpose token and auth will be used for that.
I also tested this locally, by changing auth type of change passwor and it was working as expected.
## Checklist
<!-- Put an `x` in 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
|
b2b9fab31dc838958e59a7a6755a0585d5a10302
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4475
|
Bug: Add tenant_id as a field for data pipeline
1. Add `Tenant_id` as a field for all logs
2. Add `Tenant_id` action for Kafka messages as well , headers to be a combination of ( tenant_id, merchant_id, payment_id )
3. Make logical databases and physical tables in clickhouse for different tenants
|
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index c360b41a6cf..0545191318d 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1109,9 +1109,8 @@ impl QueueInterface for KafkaStore {
entry_id: &RedisEntryId,
fields: Vec<(&str, String)>,
) -> CustomResult<(), RedisError> {
- let stream_name = format!("{}_{}", &self.tenant_id.0, stream);
self.diesel_store
- .stream_append_entry(&stream_name, entry_id, fields)
+ .stream_append_entry(stream, entry_id, fields)
.await
}
|
2024-06-07T12:32:22Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
As part of multitenancy feature, we added tenant prefix in the redisinterface directly. so this specific handling of tenant id in append_stream function is not required anymore
### 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).
-->
#4475
Remove tenant id from redis stream key of kafkaStore
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Make a payment and see if the entries are added in process tracker
2. Check if the analytics for the payment is visible from the dashboard
## 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
|
d0fd7095cd4a433aa7eb51258303ef45008e28de
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4472
|
Bug: [FEATURE] Add support for sending additional metadata in the `MessagingInterface`
### Feature Description
In the current implementation of message interface I can only send a Message & a timestamp associated with the message,
There is no accomodation to send additional metadata about the message which isn't part of the data but could be propogated to the downstream implementations,
These could be used downstream as kafka headers or redis hashes or partition keys.
### Possible Implementation
metadata can be a simplistic `HashMap<String, String>` and can be either accomodated as a new param in the [`MessagingInterface`](https://github.com/juspay/hyperswitch/blob/cc1051da99c1b4e007d7f730e2fe3cb08b078d80/crates/events/src/lib.rs#L239) or a new method on the [`Message`](https://github.com/juspay/hyperswitch/blob/cc1051da99c1b4e007d7f730e2fe3cb08b078d80/crates/events/src/lib.rs#L239) Interface.
The implementers of MessageInterface can handle it as follows
1. Kafka
Send the metadata as headers
2. EventLogger
Log the metadata as a separate key along with the raw data
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/events/src/lib.rs b/crates/events/src/lib.rs
index 0136b64a0f6..cef0c8894de 100644
--- a/crates/events/src/lib.rs
+++ b/crates/events/src/lib.rs
@@ -49,6 +49,11 @@ pub trait Event: EventInfo {
/// The class/type of the event. This is used to group/categorize events together.
fn class(&self) -> Self::EventType;
+
+ /// Metadata associated with the event
+ fn metadata(&self) -> HashMap<String, String> {
+ HashMap::new()
+ }
}
/// Hold the context information for any events
@@ -73,7 +78,8 @@ where
event: E,
}
-struct RawEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A);
+/// A flattened event that flattens the context provided to it along with the actual event.
+struct FlatMapEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A);
impl<T, A, E, D> EventBuilder<T, A, E, D>
where
@@ -109,12 +115,13 @@ where
/// Emit the event.
pub fn try_emit(self) -> Result<(), EventsError> {
let ts = self.event.timestamp();
+ let metadata = self.event.metadata();
self.message_sink
- .send_message(RawEvent(self.metadata, self.event), ts)
+ .send_message(FlatMapEvent(self.metadata, self.event), metadata, ts)
}
}
-impl<T, A> Serialize for RawEvent<T, A>
+impl<T, A> Serialize for FlatMapEvent<T, A>
where
A: Event<EventType = T>,
{
@@ -236,7 +243,12 @@ pub trait MessagingInterface {
/// The type of the event used for categorization by the event publisher.
type MessageClass;
/// Send a message that follows the defined message class.
- fn send_message<T>(&self, data: T, timestamp: PrimitiveDateTime) -> Result<(), EventsError>
+ fn send_message<T>(
+ &self,
+ data: T,
+ metadata: HashMap<String, String>,
+ timestamp: PrimitiveDateTime,
+ ) -> Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize;
}
@@ -252,7 +264,7 @@ pub trait Message {
fn identifier(&self) -> String;
}
-impl<T, A> Message for RawEvent<T, A>
+impl<T, A> Message for FlatMapEvent<T, A>
where
A: Event<EventType = T>,
{
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index e1ecd09804c..1af515b8c22 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use error_stack::ResultExt;
use events::{EventsError, Message, MessagingInterface};
use hyperswitch_domain_models::errors::{StorageError, StorageResult};
@@ -94,14 +96,15 @@ impl MessagingInterface for EventsHandler {
fn send_message<T>(
&self,
data: T,
+ metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize,
{
match self {
- Self::Kafka(a) => a.send_message(data, timestamp),
- Self::Logs(a) => a.send_message(data, timestamp),
+ Self::Kafka(a) => a.send_message(data, metadata, timestamp),
+ Self::Logs(a) => a.send_message(data, metadata, timestamp),
}
}
}
diff --git a/crates/router/src/events/event_logger.rs b/crates/router/src/events/event_logger.rs
index 235ee4a3e3c..004f94942d2 100644
--- a/crates/router/src/events/event_logger.rs
+++ b/crates/router/src/events/event_logger.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use events::{EventsError, Message, MessagingInterface};
use masking::ErasedMaskSerialize;
use time::PrimitiveDateTime;
@@ -21,12 +23,13 @@ impl MessagingInterface for EventLogger {
fn send_message<T>(
&self,
data: T,
+ metadata: HashMap<String, String>,
_timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize,
{
- logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event");
+ logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event", metadata = ?metadata);
Ok(())
}
}
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index e0a4f80908d..e1601f8bbbe 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -157,7 +157,8 @@ where
payment_method = Empty,
status_code = Empty,
flow = "UNKNOWN",
- golden_log_line = Empty
+ golden_log_line = Empty,
+ tenant_id = "ta"
)
.or_current(),
),
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 3523ab9261f..9c38917424e 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -1,4 +1,4 @@
-use std::sync::Arc;
+use std::{collections::HashMap, sync::Arc};
use bigdecimal::ToPrimitive;
use common_utils::errors::CustomResult;
@@ -6,6 +6,7 @@ use error_stack::{report, ResultExt};
use events::{EventsError, Message, MessagingInterface};
use rdkafka::{
config::FromClientConfig,
+ message::{Header, OwnedHeaders},
producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer},
};
#[cfg(feature = "payouts")]
@@ -528,6 +529,7 @@ impl MessagingInterface for KafkaProducer {
fn send_message<T>(
&self,
data: T,
+ metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
@@ -538,12 +540,20 @@ impl MessagingInterface for KafkaProducer {
.masked_serialize()
.and_then(|i| serde_json::to_vec(&i))
.change_context(EventsError::SerializationError)?;
+ let mut headers = OwnedHeaders::new();
+ for (k, v) in metadata.iter() {
+ headers = headers.insert(Header {
+ key: k.as_str(),
+ value: Some(v),
+ });
+ }
self.producer
.0
.send(
BaseRecord::to(topic)
.key(&data.identifier())
.payload(&json_data)
+ .headers(headers)
.timestamp(
(timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000)
.to_i64()
|
2024-06-04T14:21:27Z
|
## 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 -->
- Allow setting kafka headers in message
### 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)?
-->
<img width="1597" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/67529c15-c762-465d-a02a-fab090676c3a">
## 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
|
a2ea0ed19c075fb0e23b16ddc24b5230dc70369b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4467
|
Bug: [FEATURE] [CRYPTOPAY] Report underpaid/overpaid amount in outgoing webhooks
### Feature Description
During settlement, payments processed through the Cryptopay connector may experience underpayment or overpayment, leading to fluctuations in the payment amount. The revised amount must be communicated through outgoing webhooks for the respective payment.
### Possible Implementation
The new `price_amount` should be populated in `amount_captured` field.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index 2f9c996eff4..7245694bd44 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -287,11 +287,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
+ types::RouterData::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.currency,
+ ))
}
fn get_error_response(
@@ -371,11 +374,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
+ types::RouterData::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.currency,
+ ))
}
fn get_error_response(
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index e6db0cf320c..b8f398a0d96 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -1,8 +1,10 @@
use common_utils::pii;
+use error_stack::ResultExt;
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
+use super::utils as connector_utils;
use crate::{
connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData},
consts,
@@ -146,17 +148,17 @@ pub struct CryptopayPaymentsResponse {
}
impl<F, T>
- TryFrom<types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+ TryFrom<(
+ types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ diesel_models::enums::Currency,
+ )> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CryptopayPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ (item, currency): (
+ types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ diesel_models::enums::Currency,
+ ),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
let response = if is_payment_failure(status) {
@@ -197,11 +199,28 @@ impl<F, T>
incremental_authorization_allowed: None,
})
};
- Ok(Self {
- status,
- response,
- ..item.data
- })
+
+ match item.response.data.price_amount {
+ Some(price_amount) => {
+ let amount_captured = Some(
+ connector_utils::to_currency_lower_unit(price_amount, currency)?
+ .parse::<i64>()
+ .change_context(errors::ConnectorError::ParsingFailed)?,
+ );
+
+ Ok(Self {
+ status,
+ response,
+ amount_captured,
+ ..item.data
+ })
+ }
+ None => Ok(Self {
+ status,
+ response,
+ ..item.data
+ }),
+ }
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 23b3f1f6931..c8de432fc0c 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1220,6 +1220,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
None => types::SyncRequestType::SinglePaymentSync,
},
payment_method_type: payment_data.payment_attempt.payment_method_type,
+ currency: payment_data.currency,
})
}
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 6004131be40..951be887ed1 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -565,6 +565,7 @@ pub struct PaymentsSyncData {
pub sync_type: SyncRequestType,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub currency: storage_enums::Currency,
}
#[derive(Debug, Default, Clone)]
diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs
index 46f61271ee4..5cd82d097aa 100644
--- a/crates/router/tests/connectors/bambora.rs
+++ b/crates/router/tests/connectors/bambora.rs
@@ -109,6 +109,7 @@ async fn should_sync_authorized_payment() {
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
None,
)
@@ -224,6 +225,7 @@ async fn should_sync_auto_captured_payment() {
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
None,
)
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index c7934b3711a..c58cab38a22 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -157,6 +157,7 @@ async fn should_sync_authorized_payment() {
connector_meta: None,
mandate_id: None,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs
index 7f42048c981..5948855ae8d 100644
--- a/crates/router/tests/connectors/nexinets.rs
+++ b/crates/router/tests/connectors/nexinets.rs
@@ -125,6 +125,7 @@ async fn should_sync_authorized_payment() {
connector_meta,
mandate_id: None,
payment_method_type: None,
+ currency: enums::Currency::EUR,
}),
None,
)
diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs
index 14690ae2a73..bded135f45d 100644
--- a/crates/router/tests/connectors/paypal.rs
+++ b/crates/router/tests/connectors/paypal.rs
@@ -142,6 +142,7 @@ async fn should_sync_authorized_payment() {
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
get_default_payment_info(),
)
@@ -339,6 +340,7 @@ async fn should_sync_auto_captured_payment() {
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 47ec71cc94e..6294108c820 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -997,6 +997,7 @@ impl Default for PaymentSyncType {
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
+ currency: enums::Currency::USD,
};
Self(data)
}
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index c9a7be2b0a6..95017e7da0e 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -104,6 +104,7 @@ async fn should_sync_authorized_payment() {
connector_meta: None,
mandate_id: None,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
None,
)
@@ -219,6 +220,7 @@ async fn should_sync_auto_captured_payment() {
connector_meta: None,
mandate_id: None,
payment_method_type: None,
+ currency: enums::Currency::USD,
}),
None,
)
|
2024-04-26T05:58:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
During settlement, payments processed through the Cryptopay connector may experience underpayment or overpayment, leading to fluctuations in the payment amount. The revised amount must be communicated through outgoing webhooks for the respective payment.
The new `price_amount` should be populated in `amount_captured` field.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4467
## How did you test 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 check for the `amount_received` in outgoing webhook for underpaid/overpaid payments via cryptopay. The `amount_received` should be equal to the `invoice amount` on cryptopay dashboard for that payment.
In order to generate an underpaid/overpaid one must let the 10 min timer runout (on the redirection screen) and then only complete the payment.
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_pjVrtRQmn0UDgtRtnzq6irFdNrbGHTgMvHFhX2RI15o84A5UFWvtlstAyB14V349' \
--data-raw '{
"amount": 120,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC"
}
}
}'
```
Response:
```
{
"payment_id": "pay_Ay8enoELqeEY9qlS1tXk",
"merchant_id": "merchant_1713942708",
"status": "requires_customer_action",
"amount": 120,
"net_amount": 120,
"amount_capturable": 120,
"amount_received": 120,
"connector": "cryptopay",
"client_secret": "pay_Ay8enoELqeEY9qlS1tXk_secret_vTv6nv9uEHpNf7zSQgav",
"created": "2024-04-26T07:13:48.793Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_Ay8enoELqeEY9qlS1tXk/merchant_1713942708/pay_Ay8enoELqeEY9qlS1tXk_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "3c40efd2-2ade-4151-8760-aabb20a299fe",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_Ay8enoELqeEY9qlS1tXk_1",
"payment_link": null,
"profile_id": "pro_HgGSGQyaRys8iaDsi7OX",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_z8isFAS0iNcgES4VN5Lm",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-26T07:28:48.793Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-04-26T07:13:49.156Z"
}
```
Outgoing Webhook:

Cryptopay 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
- [ ] I added unit tests for my changes where possible
|
b2b9fab31dc838958e59a7a6755a0585d5a10302
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4463
|
Bug: [REFACTOR]: handle network delays with expiry of access token
It may so happen that there might be a slight delay in the network to receive the access token from connector. So when we store the access token with expiry already few seconds would have elapsed. So the key might expire few seconds before than the actual expiry at hyperswitch.
**Note** - This affects only to those connectors which provide relative expiry i.e expires in 300s.
In order to account for this, when storing the redis expiry key, it can be set by subtracting few seconds from the actual expiry in order to account for the network delays.
**Note** - This can be done in the core level for all access token in order to be safe. There might also be some network delays when using this access token to create the payment. The token might have not been expired when the request is sent, but once it reaches the processor, it might have been expired.
|
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 0c9e9443ac9..6d9da8f7bb5 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -118,6 +118,8 @@ pub const POLL_ID_TTL: i64 = 900;
pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2;
pub const DEFAULT_POLL_FREQUENCY: i8 = 5;
+// Number of seconds to subtract from access token expiry
+pub(crate) const REDUCE_ACCESS_TOKEN_EXPIRY_TIME: u8 = 15;
pub const CONNECTOR_CREDS_TOKEN_TTL: i64 = 900;
//max_amount allowed is 999999999 in minor units
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index 2d4ed2b6e1b..0c5aa13eb2f 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -91,9 +91,26 @@ pub async fn add_access_token<
connector.connector_name,
access_token.expires
);
+ metrics::ACCESS_TOKEN_CACHE_HIT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.connector_name.to_string(),
+ )],
+ );
Ok(Some(access_token))
}
None => {
+ metrics::ACCESS_TOKEN_CACHE_MISS.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ connector.connector_name.to_string(),
+ )],
+ );
+
let cloned_router_data = router_data.clone();
let refresh_token_request_data = types::AccessTokenRequestData::try_from(
router_data.connector_auth_type.clone(),
@@ -123,15 +140,31 @@ pub async fn add_access_token<
&refresh_token_router_data,
)
.await?
- .async_map(|access_token| async {
- // Store the access token in redis with expiry
- // The expiry should be adjusted for network delays from the connector
+ .async_map(|access_token| async move {
let store = &*state.store;
+
+ // The expiry should be adjusted for network delays from the connector
+ // The access token might not have been expired when request is sent
+ // But once it reaches the connector, it might expire because of the network delay
+ // Subtract few seconds from the expiry in order to account for these network delays
+ // This will reduce the expiry time by `REDUCE_ACCESS_TOKEN_EXPIRY_TIME` seconds
+ let modified_access_token_with_expiry = types::AccessToken {
+ expires: access_token
+ .expires
+ .saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()),
+ ..access_token
+ };
+
+ logger::debug!(
+ access_token_expiry_after_modification =
+ modified_access_token_with_expiry.expires
+ );
+
if let Err(access_token_set_error) = store
.set_access_token(
merchant_id,
&merchant_connector_id_or_connector_name,
- access_token.clone(),
+ modified_access_token_with_expiry.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -142,7 +175,7 @@ pub async fn add_access_token<
// The next request will create new access token, if required
logger::error!(access_token_set_error=?access_token_set_error);
}
- Some(access_token)
+ Some(modified_access_token_with_expiry)
})
.await
}
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 780dd51bbde..1123be1a874 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -52,7 +52,6 @@ counter_metric!(MCA_CREATE, GLOBAL_METER);
// Flow Specific Metrics
-counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER);
histogram_metric!(CONNECTOR_REQUEST_TIME, GLOBAL_METER);
counter_metric!(SESSION_TOKEN_CREATED, GLOBAL_METER);
@@ -123,5 +122,16 @@ counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process trac
counter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process tracker
counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow
+// Access token metrics
+//
+// A counter to indicate the number of new access tokens created
+counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER);
+
+// A counter to indicate the access token cache hits
+counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER);
+
+// A counter to indicate the access token cache miss
+counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER);
+
pub mod request;
pub mod utils;
|
2024-05-09T18:56:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Refactoring
## Description
<!-- Describe your changes in detail -->
There might be some delay in network due to which the access token which was not expired locally, might have expired when it reaches the connector. This PR reduces the expiry of access token in order to account for such delays
<!--
Provide links to the files with corresponding 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 payment with any connector which supports access token and then check the ttl in redis.
<img width="2052" alt="Screenshot 2024-05-10 at 12 24 52 AM" src="https://github.com/juspay/hyperswitch/assets/48803246/1ef1d233-d0c0-4f6d-a511-b80e61805513">
- The below log can also be checked
<img width="1284" alt="Screenshot 2024-05-10 at 12 25 58 AM" src="https://github.com/juspay/hyperswitch/assets/48803246/b69f742f-9f22-4960-a446-12e77ac03769">
## IMPACT
- airwallex
- globalpay
- paypal
- payu
- trustpay - bank redirect
- iatapay
- volt
## Checklist
<!-- Put an `x` in 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
|
4b5b558dae8d2fefb66b8b16c486f07e3e800758
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4464
|
Bug: refactor: deprecate V1 signin, verify email and invite APIs
Currently the following endpoints are not being used by the dashboard
`/user/signin`
`/user/verify_email`
`/user/invite`
New APIs are created for the above APIs which are
`/user/v2/signin`
`/user/v2/verify_email`
`/user/invite_multiple`
The old APIs are kept for backwards compatibility, as the movement is completed entirely from the FE side as well, old APIs can be removed.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 4ef04981572..9884dbc4f41 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -12,9 +12,9 @@ use crate::user::{
},
AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetUserDetailsRequest, GetUserDetailsResponse, InviteUserRequest, InviteUserResponse,
- ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest,
- SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
+ GetUserDetailsRequest, GetUserDetailsResponse, InviteUserRequest, ListUsersResponse,
+ ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest, SignInResponse,
+ SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest,
};
@@ -54,7 +54,6 @@ common_utils::impl_misc_api_event_type!(
ForgotPasswordRequest,
ResetPasswordRequest,
InviteUserRequest,
- InviteUserResponse,
ReInviteUserRequest,
VerifyEmailRequest,
SendVerifyEmailRequest,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index afe55afb276..9b3d7a2e654 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -98,12 +98,6 @@ pub struct InviteUserRequest {
pub role_id: String,
}
-#[derive(Debug, serde::Serialize)]
-pub struct InviteUserResponse {
- pub is_email_sent: bool,
- pub password: Option<Secret<String>>,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct InviteMultipleUserResponse {
pub email: pii::Email,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 54db6d11e7f..71d18774cb8 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -100,34 +100,6 @@ pub async fn signup(
auth::cookies::set_cookie_response(response, token)
}
-pub async fn signin_without_invite_checks(
- state: AppState,
- request: user_api::SignInRequest,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- let user_from_db: domain::UserFromStorage = state
- .store
- .find_user_by_email(&request.email)
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::InvalidCredentials)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?
- .into();
-
- user_from_db.compare_password(request.password)?;
-
- let user_role = user_from_db.get_role_from_db(state.clone()).await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
- auth::cookies::set_cookie_response(response, token)
-}
-
pub async fn signin(
state: AppState,
request: user_api::SignInRequest,
@@ -424,206 +396,6 @@ pub async fn reset_password(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn invite_user(
- state: AppState,
- request: user_api::InviteUserRequest,
- user_from_token: auth::UserFromToken,
- req_state: ReqState,
-) -> UserResponse<user_api::InviteUserResponse> {
- let inviter_user = state
- .store
- .find_user_by_id(user_from_token.user_id.as_str())
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- if inviter_user.email == request.email {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "User Inviting themselves".to_string(),
- )
- .into());
- }
-
- let role_info = roles::RoleInfo::from_role_id(
- &state,
- &request.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .to_not_found_response(UserErrors::InvalidRoleId)?;
-
- if !role_info.is_invitable() {
- return Err(report!(UserErrors::InvalidRoleId))
- .attach_printable(format!("role_id = {} is not invitable", request.role_id));
- }
-
- let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
-
- let invitee_user = state
- .store
- .find_user_by_email(&invitee_email.clone().into_inner())
- .await;
-
- if let Ok(invitee_user) = invitee_user {
- let invitee_user_from_db = domain::UserFromStorage::from(invitee_user);
-
- let now = common_utils::date_time::now();
- state
- .store
- .insert_user_role(UserRoleNew {
- user_id: invitee_user_from_db.get_user_id().to_owned(),
- merchant_id: user_from_token.merchant_id.clone(),
- role_id: request.role_id,
- org_id: user_from_token.org_id,
- status: {
- if cfg!(feature = "email") {
- UserStatus::InvitationSent
- } else {
- UserStatus::Active
- }
- },
- created_by: user_from_token.user_id.clone(),
- last_modified_by: user_from_token.user_id,
- created_at: now,
- last_modified: now,
- })
- .await
- .map_err(|e| {
- if e.current_context().is_db_unique_violation() {
- e.change_context(UserErrors::UserExists)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
-
- let is_email_sent;
- #[cfg(feature = "email")]
- {
- let email_contents = email_types::InviteRegisteredUser {
- recipient_email: invitee_email,
- user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
- settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id,
- };
-
- is_email_sent = state
- .email_client
- .compose_and_send_email(
- Box::new(email_contents),
- state.conf.proxy.https_url.as_ref(),
- )
- .await
- .map(|email_result| logger::info!(?email_result))
- .map_err(|email_result| logger::error!(?email_result))
- .is_ok();
- }
- #[cfg(not(feature = "email"))]
- {
- is_email_sent = false;
- }
- Ok(ApplicationResponse::Json(user_api::InviteUserResponse {
- is_email_sent,
- password: None,
- }))
- } else if invitee_user
- .as_ref()
- .map_err(|e| e.current_context().is_db_not_found())
- .err()
- .unwrap_or(false)
- {
- let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?;
-
- new_user
- .insert_user_in_db(state.store.as_ref())
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let invitation_status = if cfg!(feature = "email") {
- UserStatus::InvitationSent
- } else {
- UserStatus::Active
- };
-
- let now = common_utils::date_time::now();
- state
- .store
- .insert_user_role(UserRoleNew {
- user_id: new_user.get_user_id().to_owned(),
- merchant_id: user_from_token.merchant_id.clone(),
- role_id: request.role_id.clone(),
- org_id: user_from_token.org_id.clone(),
- status: invitation_status,
- created_by: user_from_token.user_id.clone(),
- last_modified_by: user_from_token.user_id,
- created_at: now,
- last_modified: now,
- })
- .await
- .map_err(|e| {
- if e.current_context().is_db_unique_violation() {
- e.change_context(UserErrors::UserExists)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
-
- let is_email_sent;
- #[cfg(feature = "email")]
- {
- // Doing this to avoid clippy lints
- // will add actual usage for this later
- let _ = req_state.clone();
- let email_contents = email_types::InviteUser {
- recipient_email: invitee_email,
- user_name: domain::UserName::new(new_user.get_name())?,
- settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id,
- };
- let send_email_result = state
- .email_client
- .compose_and_send_email(
- Box::new(email_contents),
- state.conf.proxy.https_url.as_ref(),
- )
- .await;
- logger::info!(?send_email_result);
- is_email_sent = send_email_result.is_ok();
- }
- #[cfg(not(feature = "email"))]
- {
- is_email_sent = false;
- let invited_user_token = auth::UserFromToken {
- user_id: new_user.get_user_id(),
- merchant_id: user_from_token.merchant_id,
- org_id: user_from_token.org_id,
- role_id: request.role_id,
- };
-
- let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
- dashboard_metadata::set_metadata(
- state.clone(),
- invited_user_token,
- set_metadata_request,
- req_state,
- )
- .await?;
- }
-
- Ok(ApplicationResponse::Json(user_api::InviteUserResponse {
- is_email_sent,
- password: if cfg!(not(feature = "email")) {
- Some(new_user.get_password().get_secret())
- } else {
- None
- },
- }))
- } else {
- Err(report!(UserErrors::InternalServerError))
- }
-}
-
pub async fn invite_multiple_user(
state: AppState,
user_from_token: auth::UserFromToken,
@@ -1317,44 +1089,6 @@ pub async fn list_users_for_merchant_account(
)))
}
-#[cfg(feature = "email")]
-pub async fn verify_email_without_invite_checks(
- state: AppState,
- req: user_api::VerifyEmailRequest,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- let token = req.token.clone().expose();
- let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
- auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
- let user = state
- .store
- .find_user_by_email(
- &email_token
- .get_email()
- .change_context(UserErrors::InternalServerError)?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
- let user = state
- .store
- .update_user_by_user_id(user.user_id.as_str(), storage_user::UserUpdate::VerifyUser)
- .await
- .change_context(UserErrors::InternalServerError)?;
- let user_from_db: domain::UserFromStorage = user.into();
- let user_role = user_from_db.get_role_from_db(state.clone()).await?;
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|e| logger::error!(?e));
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
-
- let response =
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
-
- auth::cookies::set_cookie_response(response, token)
-}
-
#[cfg(feature = "email")]
pub async fn verify_email(
state: AppState,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ff660dbf7b7..10021b6c285 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1153,9 +1153,6 @@ impl User {
let mut route = web::scope("/user").app_data(web::Data::new(state));
route = route
- .service(
- web::resource("/signin").route(web::post().to(user_signin_without_invite_checks)),
- )
.service(web::resource("/v2/signin").route(web::post().to(user_signin)))
.service(web::resource("/signout").route(web::post().to(signout)))
.service(web::resource("/change_password").route(web::post().to(change_password)))
@@ -1188,10 +1185,6 @@ impl User {
web::resource("/signup_with_merchant_id")
.route(web::post().to(user_signup_with_merchant_id)),
)
- .service(
- web::resource("/verify_email")
- .route(web::post().to(verify_email_without_invite_checks)),
- )
.service(web::resource("/v2/verify_email").route(web::post().to(verify_email)))
.service(
web::resource("/verify_email_request")
@@ -1215,7 +1208,6 @@ impl User {
.service(
web::resource("/list").route(web::get().to(list_users_for_merchant_account)),
)
- .service(web::resource("/invite").route(web::post().to(invite_user)))
.service(
web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)),
)
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index aec3a5f2c1f..cc76ae0b3b4 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -183,7 +183,6 @@ impl From<Flow> for ApiIdentifier {
Flow::UserConnectAccount
| Flow::UserSignUp
- | Flow::UserSignInWithoutInviteChecks
| Flow::UserSignIn
| Flow::Signout
| Flow::ChangePassword
@@ -200,11 +199,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListUsersForMerchantAccount
| Flow::ForgotPassword
| Flow::ResetPassword
- | Flow::InviteUser
| Flow::InviteMultipleUser
| Flow::ReInviteUser
| Flow::UserSignUpWithMerchantId
- | Flow::VerifyEmailWithoutInviteChecks
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index eb34c8ae321..bf3ddbc4491 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -58,25 +58,6 @@ pub async fn user_signup(
.await
}
-pub async fn user_signin_without_invite_checks(
- state: web::Data<AppState>,
- http_req: HttpRequest,
- json_payload: web::Json<user_api::SignInRequest>,
-) -> HttpResponse {
- let flow = Flow::UserSignInWithoutInviteChecks;
- let req_payload = json_payload.into_inner();
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- req_payload.clone(),
- |state, _, req_body, _| user_core::signin_without_invite_checks(state, req_body),
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn user_signin(
state: web::Data<AppState>,
http_req: HttpRequest,
@@ -383,24 +364,6 @@ pub async fn reset_password(
))
.await
}
-
-pub async fn invite_user(
- state: web::Data<AppState>,
- req: HttpRequest,
- payload: web::Json<user_api::InviteUserRequest>,
-) -> HttpResponse {
- let flow = Flow::InviteUser;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- |state, user, payload, req_state| user_core::invite_user(state, payload, user, req_state),
- &auth::JWTAuth(Permission::UsersWrite),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
pub async fn invite_multiple_user(
state: web::Data<AppState>,
req: HttpRequest,
@@ -457,27 +420,6 @@ pub async fn accept_invite_from_email(
.await
}
-#[cfg(feature = "email")]
-pub async fn verify_email_without_invite_checks(
- state: web::Data<AppState>,
- http_req: HttpRequest,
- json_payload: web::Json<user_api::VerifyEmailRequest>,
-) -> HttpResponse {
- let flow = Flow::VerifyEmailWithoutInviteChecks;
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- json_payload.into_inner(),
- |state, _, req_payload, _| {
- user_core::verify_email_without_invite_checks(state, req_payload)
- },
- &auth::NoAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
#[cfg(feature = "email")]
pub async fn verify_email(
state: web::Data<AppState>,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 0ec6894debe..0cb00c1a854 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -302,8 +302,6 @@ pub enum Flow {
UserSignUp,
/// User Sign Up
UserSignUpWithMerchantId,
- /// User Sign In without invite checks
- UserSignInWithoutInviteChecks,
/// User Sign In
UserSignIn,
/// User connect account
@@ -362,8 +360,6 @@ pub enum Flow {
ForgotPassword,
/// Reset password using link
ResetPassword,
- /// Invite users
- InviteUser,
/// Invite multiple users
InviteMultipleUser,
/// Reinvite user
@@ -380,8 +376,6 @@ pub enum Flow {
SyncOnboardingStatus,
/// Reset tracking id
ResetTrackingId,
- /// Verify email token without invite checks
- VerifyEmailWithoutInviteChecks,
/// Verify email Token
VerifyEmail,
/// Send verify email
|
2024-04-25T09:18:00Z
|
## 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 will remove the following endpoints and corresponding APIs
`/user/signin`
`/user/verify_email`
`/user/invite`
### 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 #4464
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data '{
"email": "user email",
"password": "password"
}'
```
```
curl --location 'http://localhost:8080/user/verify_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"email": "email",
"name": "name",
"role_id": "merchant_view_only"
}'
```
When these curls are hit, BE will respond with 404 Not Found with the following body
```
{
"error": {
"type": "invalid_request",
"message": "Unrecognized request URL",
"code": "IR_02"
}
}
```
## Checklist
<!-- Put an `x` in 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
|
2848e0a3e333ef292130abbeec362f092446270c
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4461
|
Bug: [REFACTOR]: use `merchant_connector_id` for storing `access_token`
The access tokens are currently stored in the format of `access_token_{merchant_id}_{connector_name}`. This cannot support multiple connector accounts.
In order to store access tokens for multiple connector accounts in a single business profile or a merchant account, the new format in which this should be stored is
`access_token_{merchant_id}_{merchant_connector_id}`
But there are cases when `merchant_connector_id` may not be present
- In cases where straight through routing algorithm is used
- In cases where the credentials are supplied directly using the creds identifier
In order to support these use cases, a fallback should be provided.
|
diff --git a/crates/common_utils/src/access_token.rs b/crates/common_utils/src/access_token.rs
new file mode 100644
index 00000000000..20bac0dafbb
--- /dev/null
+++ b/crates/common_utils/src/access_token.rs
@@ -0,0 +1,11 @@
+//! Commonly used utilities for access token
+
+use std::fmt::Display;
+
+/// Create a key for fetching the access token from redis
+pub fn create_access_token_key(
+ merchant_id: impl Display,
+ merchant_connector_id: impl Display,
+) -> String {
+ format!("access_token_{merchant_id}_{merchant_connector_id}")
+}
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index e30d596d9a7..f24b67fde1b 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -2,6 +2,7 @@
#![warn(missing_docs, missing_debug_implementations)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
+pub mod access_token;
pub mod consts;
pub mod crypto;
pub mod custom_serde;
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index 47f6b7e2ae4..49d27d81509 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -10,7 +10,7 @@ use crate::{
payments,
},
routes::{metrics, AppState},
- services,
+ services::{self, logger},
types::{self, api as api_types, domain},
};
@@ -64,8 +64,14 @@ pub async fn add_access_token<
{
let merchant_id = &merchant_account.merchant_id;
let store = &*state.store;
+ let merchant_connector_id = connector
+ .merchant_connector_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Missing merchant_connector_id in ConnectorData")?;
+
let old_access_token = store
- .get_access_token(merchant_id, connector.connector.id())
+ .get_access_token(merchant_id, merchant_connector_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
@@ -103,19 +109,24 @@ pub async fn add_access_token<
)
.await?
.async_map(|access_token| async {
- //Store the access token in db
+ // Store the access token in redis with expiry
+ // The expiry should be adjusted for network delays from the connector
let store = &*state.store;
- // This error should not be propagated, we don't want payments to fail once we have
- // the access token, the next request will create new access token
- let _ = store
+ if let Err(access_token_set_error) = store
.set_access_token(
merchant_id,
- connector.connector.id(),
+ merchant_connector_id.as_str(),
access_token.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("DB error when setting the access token");
+ .attach_printable("DB error when setting the access token")
+ {
+ // If we are not able to set the access token in redis, the error should just be logged and proceed with the payment
+ // Payments should not fail, once the access token is successfully created
+ // The next request will create new access token, if required
+ logger::error!(access_token_set_error=?access_token_set_error);
+ }
Some(access_token)
})
.await
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 9787e366e79..a4e73f7d2c6 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -859,21 +859,21 @@ impl ConnectorAccessToken for KafkaStore {
async fn get_access_token(
&self,
merchant_id: &str,
- connector_name: &str,
+ merchant_connector_id: &str,
) -> CustomResult<Option<AccessToken>, errors::StorageError> {
self.diesel_store
- .get_access_token(merchant_id, connector_name)
+ .get_access_token(merchant_id, merchant_connector_id)
.await
}
async fn set_access_token(
&self,
merchant_id: &str,
- connector_name: &str,
+ merchant_connector_id: &str,
access_token: AccessToken,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
- .set_access_token(merchant_id, connector_name, access_token)
+ .set_access_token(merchant_id, merchant_connector_id, access_token)
.await
}
}
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index b7c85560804..06d1e505c6b 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -24,13 +24,13 @@ pub trait ConnectorAccessToken {
async fn get_access_token(
&self,
merchant_id: &str,
- connector_name: &str,
+ merchant_connector_id: &str,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError>;
async fn set_access_token(
&self,
merchant_id: &str,
- connector_name: &str,
+ merchant_connector_id: &str,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError>;
}
@@ -41,12 +41,14 @@ impl ConnectorAccessToken for Store {
async fn get_access_token(
&self,
merchant_id: &str,
- connector_name: &str,
+ merchant_connector_id: &str,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
//TODO: Handle race condition
// This function should acquire a global lock on some resource, if access token is already
// being refreshed by other request then wait till it finishes and use the same access token
- let key = format!("access_token_{merchant_id}_{connector_name}");
+ let key =
+ common_utils::access_token::create_access_token_key(merchant_id, merchant_connector_id);
+
let maybe_token = self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
@@ -55,10 +57,9 @@ impl ConnectorAccessToken for Store {
.change_context(errors::StorageError::KVError)
.attach_printable("DB error when getting access token")?;
- let access_token: Option<types::AccessToken> = maybe_token
- .map(|token| token.parse_struct("AccessToken"))
+ let access_token = maybe_token
+ .map(|token| token.parse_struct::<types::AccessToken>("AccessToken"))
.transpose()
- .change_context(errors::ParsingError::UnknownError)
.change_context(errors::StorageError::DeserializationFailed)?;
Ok(access_token)
@@ -68,10 +69,11 @@ impl ConnectorAccessToken for Store {
async fn set_access_token(
&self,
merchant_id: &str,
- connector_name: &str,
+ merchant_connector_id: &str,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
- let key = format!("access_token_{merchant_id}_{connector_name}");
+ let key =
+ common_utils::access_token::create_access_token_key(merchant_id, merchant_connector_id);
let serialized_access_token = access_token
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
@@ -88,7 +90,7 @@ impl ConnectorAccessToken for MockDb {
async fn get_access_token(
&self,
_merchant_id: &str,
- _connector_name: &str,
+ _merchant_connector_id: &str,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
Ok(None)
}
@@ -96,7 +98,7 @@ impl ConnectorAccessToken for MockDb {
async fn set_access_token(
&self,
_merchant_id: &str,
- _connector_name: &str,
+ _merchant_connector_id: &str,
_access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
Ok(())
|
2024-04-25T08:20:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Refactoring
## Description
<!-- Describe your changes in detail -->
This PR modifies the way in which access tokens are stored in the redis. The key format is changed to
`access_token_{merchant_id}_{merchant_connector_id}` More information can be found in the linked issue.
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
In order to support multiple connector accounts
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Run the Trustpay postman collection locally and check whether the access token is stored in redis
<img width="2056" alt="Screenshot 2024-04-25 at 1 56 18 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/f527d6d4-4af9-49cf-8a3f-bf2fa6952d2c">
## Impact
- All connectors using access token auth.
- Trustpay BankRedirect, Volt and Iatapay
## Checklist
<!-- Put an `x` in 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
|
4c793c3c00e93ebf4a4db3439a213474ff57b54d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4450
|
Bug: [BUG] Audit Wallets for Cybersource
### Bug Description
Payment methods apple pay and google pay need to be audited for connector cybersource.
### Expected Behavior
https://developer.cybersource.com/content/dam/docs/cybs/en-us/apple-pay/developer/fdiglobal/rest/applepay.pdf
- `paymentInformation.fluidData.descriptor` needs to be passed in apple pay payments request
- HTML Error Response from connector needs to be handled
### Actual Behavior
- `paymentInformation.fluidData.descriptor` is not passed in apple pay payments request.
- HTML Error Response from connector is not handled.
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index 5298420cde2..39079fe9f99 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -5,7 +5,7 @@ use std::fmt::Debug;
use base64::Engine;
use common_utils::request::RequestContent;
use diesel_models::enums;
-use error_stack::{report, ResultExt};
+use error_stack::{report, Report, ResultExt};
use masking::{ExposeInterface, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
@@ -116,13 +116,10 @@ impl ConnectorCommon for Cybersource {
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: cybersource::CybersourceErrorResponse = res
- .response
- .parse_struct("Cybersource ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
- event_builder.map(|i| i.set_error_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ let response: Result<
+ cybersource::CybersourceErrorResponse,
+ Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Cybersource ErrorResponse");
let error_message = if res.status_code == 401 {
consts::CONNECTOR_UNAUTHORIZED_ERROR
@@ -130,7 +127,9 @@ impl ConnectorCommon for Cybersource {
consts::NO_ERROR_MESSAGE
};
match response {
- transformers::CybersourceErrorResponse::StandardError(response) => {
+ Ok(transformers::CybersourceErrorResponse::StandardError(response)) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
let (code, connector_reason) = match response.error_information {
Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()),
None => (
@@ -162,7 +161,9 @@ impl ConnectorCommon for Cybersource {
connector_transaction_id: None,
})
}
- transformers::CybersourceErrorResponse::AuthenticationError(response) => {
+ Ok(transformers::CybersourceErrorResponse::AuthenticationError(response)) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
@@ -172,7 +173,9 @@ impl ConnectorCommon for Cybersource {
connector_transaction_id: None,
})
}
- transformers::CybersourceErrorResponse::NotAvailableError(response) => {
+ Ok(transformers::CybersourceErrorResponse::NotAvailableError(response)) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
let error_response = response
.errors
.iter()
@@ -194,6 +197,14 @@ impl ConnectorCommon for Cybersource {
connector_transaction_id: None,
})
}
+ Err(error_msg) => {
+ event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
+ router_env::logger::error!(deserialization_error =? error_msg);
+ crate::utils::handle_json_response_deserialization_failure(
+ res,
+ "cybersource".to_owned(),
+ )
+ }
}
}
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index a3756770aeb..4c8e06b28ef 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -149,6 +149,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
PaymentInformation::ApplePayToken(ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_data.payment_data),
+ descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard {
transaction_type: TransactionType::ApplePay,
@@ -165,6 +166,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
consts::BASE64_ENGINE
.encode(google_pay_data.tokenization_data.token),
),
+ descriptor: None,
},
}),
Some(PaymentSolution::GooglePay),
@@ -370,8 +372,12 @@ pub struct MandatePaymentInformation {
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ descriptor: Option<String>,
}
+pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U";
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
@@ -1031,6 +1037,7 @@ impl
value: Secret::from(
consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token),
),
+ descriptor: None,
},
});
let processing_information =
@@ -1097,6 +1104,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_data.payment_data),
+ descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard {
transaction_type: TransactionType::ApplePay,
|
2024-04-24T10:50:44Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Following connector audit changes are done for wallets for connector Cybersource:
- `paymentInformation.fluidData.descriptor` is passed in apple pay payments request
- HTML Error Response from connector is handled
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4450
## How did you test 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 flow apple payments need to be tested via cybersource.
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 1900,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "food",
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data": "APPLE_PAY_TOKEN_HERE",
"payment_method": {
"display_name": "MasterCard 0839",
"network": "MasterCard",
"type": "credit"
},
"transaction_identifier": "47417dd24e81e22af0521800f4be217ee1d2424b513d39c10d3351dc849363a5"
}
}
}
}
'
```
Response:
```
{
"payment_id": "pay_blKSyuvXMdhAE8Sd2Kz3",
"merchant_id": "merchant_1709635075",
"status": "succeeded",
"amount": 1900,
"net_amount": 1900,
"amount_capturable": 0,
"amount_received": 1900,
"connector": "cybersource",
"client_secret": "pay_blKSyuvXMdhAE8Sd2Kz3_secret_VZtPAKUjXzo5wrZqGKuR",
"created": "2024-04-24T10:57:50.791Z",
"currency": "USD",
"customer_id": "custhype1232",
"customer": {
"id": "custhype1232",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "apple_pay",
"connector_label": "cybersource_US_food_default",
"business_country": "US",
"business_label": "food",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype1232",
"created_at": 1713956270,
"expires": 1713959870,
"secret": "epk_8a87d76cbb3c4958950df7a299f11102"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7139562721516032004951",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_blKSyuvXMdhAE8Sd2Kz3_1",
"payment_link": null,
"profile_id": "pro_dMJfhV51DYUbzCBKrQDw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-24T11:12:50.790Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-04-24T10:57:54.088Z"
}
```
<img width="1496" alt="Screenshot 2024-04-24 at 4 34 45 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/a007c4e0-62b7-4d3b-ade6-c79272f69e54">
Bad Request Error(this cannot be tested on sbx):
<img width="1219" alt="Screenshot 2024-04-24 at 5 01 41 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/3848cc20-3598-4df5-8416-5b4b72f212d9">

## Checklist
<!-- Put an `x` in 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
|
1d0d94d5e6528534ce461db39620f35490582ecb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4449
|
Bug: Remove repetitive words
### Bug Description
There are some repeated words in the code. Delete them to make the reading smoother and the code more elegant.
For https://github.com/juspay/hyperswitch/pull/4448
### Expected Behavior
No
### Actual Behavior
remove repetitive words
### Steps To Reproduce
remove repetitive words
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index e8f40255697..1076cbdc196 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -286,7 +286,7 @@ cards = [
]
# Scheduler settings provides a point to modify the behaviour of scheduler flow.
-# It defines the the streams/queues name and configuration as well as event selection variables
+# It defines the streams/queues name and configuration as well as event selection variables
[scheduler]
stream = "SCHEDULER_STREAM"
graceful_shutdown_interval = 60000 # Specifies how much time to wait while re-attempting shutdown for a service (in milliseconds)
diff --git a/config/deployments/scheduler/consumer.toml b/config/deployments/scheduler/consumer.toml
index cdd60552668..0251b6a764f 100644
--- a/config/deployments/scheduler/consumer.toml
+++ b/config/deployments/scheduler/consumer.toml
@@ -1,5 +1,5 @@
# Scheduler settings provides a point to modify the behaviour of scheduler flow.
-# It defines the the streams/queues name and configuration as well as event selection variables
+# It defines the streams/queues name and configuration as well as event selection variables
[scheduler]
consumer_group = "scheduler_group"
graceful_shutdown_interval = 60000 # Specifies how much time to wait while re-attempting shutdown for a service (in milliseconds)
diff --git a/config/deployments/scheduler/producer.toml b/config/deployments/scheduler/producer.toml
index 9cbaee96f03..0b16b8ffb8a 100644
--- a/config/deployments/scheduler/producer.toml
+++ b/config/deployments/scheduler/producer.toml
@@ -1,5 +1,5 @@
# Scheduler settings provides a point to modify the behaviour of scheduler flow.
-# It defines the the streams/queues name and configuration as well as event selection variables
+# It defines the streams/queues name and configuration as well as event selection variables
[scheduler]
consumer_group = "scheduler_group"
graceful_shutdown_interval = 60000 # Specifies how much time to wait while re-attempting shutdown for a service (in milliseconds)
diff --git a/config/tempo.yaml b/config/tempo.yaml
index 679d6431f5b..76dd45c497a 100644
--- a/config/tempo.yaml
+++ b/config/tempo.yaml
@@ -27,7 +27,7 @@ storage:
v2_index_downsample_bytes: 1000 # number of bytes per index record
v2_encoding: zstd # block encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2
wal:
- path: /tmp/tempo/wal # where to store the the wal locally
+ path: /tmp/tempo/wal # where to store the wal locally
v2_encoding: snappy # wal encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2
local:
path: /tmp/tempo/blocks
diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs
index 1d389f58298..07552cb519f 100644
--- a/crates/external_services/src/email.rs
+++ b/crates/external_services/src/email.rs
@@ -95,7 +95,7 @@ pub struct EmailContents {
/// The subject of email
pub subject: String,
- /// This will be the intermediate representation of the the email body in a generic format.
+ /// This will be the intermediate representation of the email body in a generic format.
/// The email clients can convert this intermediate representation to their client specific rich text format
pub body: IntermediateString,
diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs
index 1e5413bc838..79785563f3c 100644
--- a/crates/router/src/connector/globalpay/requests.rs
+++ b/crates/router/src/connector/globalpay/requests.rs
@@ -337,7 +337,7 @@ pub struct Card {
pub expiry_year: Secret<String>,
/// Indicates whether the card is a debit or credit card.
pub funding: Option<Funding>,
- /// The the card account number used to authorize the transaction. Also known as PAN.
+ /// The card account number used to authorize the transaction. Also known as PAN.
pub number: cards::CardNumber,
/// Contains the pin block info, relating to the pin code the Payer entered.
pub pin_block: Option<Secret<String>>,
@@ -776,7 +776,7 @@ pub enum Model {
Unscheduled,
}
-/// The reason stored credentials are being used to to create a transaction.
+/// The reason stored credentials are being used to create a transaction.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
diff --git a/crates/router_env/src/metrics.rs b/crates/router_env/src/metrics.rs
index 961e0d36220..e145caace00 100644
--- a/crates/router_env/src/metrics.rs
+++ b/crates/router_env/src/metrics.rs
@@ -11,7 +11,7 @@ macro_rules! metrics_context {
};
}
-/// Create a global [`Meter`][Meter] with the specified name and and an optional description.
+/// Create a global [`Meter`][Meter] with the specified name and an optional description.
///
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
diff --git a/loadtest/config/tempo.yaml b/loadtest/config/tempo.yaml
index f3e573a2bb3..135c4bac8de 100644
--- a/loadtest/config/tempo.yaml
+++ b/loadtest/config/tempo.yaml
@@ -27,7 +27,7 @@ storage:
index_downsample_bytes: 1000 # number of bytes per index record
encoding: zstd # block encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2
wal:
- path: /tmp/tempo/wal # where to store the the wal locally
+ path: /tmp/tempo/wal # where to store the wal locally
encoding: snappy # wal encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2
local:
path: /tmp/tempo/blocks
|
2024-04-24T07:44:14Z
|
The related issue: https://github.com/juspay/hyperswitch/issues/4449
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] 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
|
56f14b935d5e9742a894408a714033318ecb6f2a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4446
|
Bug: [FEATURE] Add toggle for extended card bin
### Feature Description
Add toggle for displaying extended card bin in PaymentResposne
### Possible Implementation
Add toggle for displaying extended card bin in PaymentResposne
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index b62d3afd4a8..5e03033977e 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -243,10 +243,11 @@ where
})
.collect::<Vec<_>>()
.concat();
+
let additional_payment_data = match &payment_data.payment_method_data {
Some(pmd) => {
let additional_payment_data =
- get_additional_payment_data(pmd, db).await;
+ get_additional_payment_data(pmd, db, &profile_id).await;
Some(additional_payment_data)
}
None => payment_data
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 702b63b5c08..d2a2896de8c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3649,11 +3649,23 @@ mod test {
pub async fn get_additional_payment_data(
pm_data: &api_models::payments::PaymentMethodData,
db: &dyn StorageInterface,
+ profile_id: &str,
) -> api_models::payments::AdditionalPaymentData {
match pm_data {
api_models::payments::PaymentMethodData::Card(card_data) => {
let card_isin = Some(card_data.card_number.clone().get_card_isin());
- let card_extended_bin = Some(card_data.card_number.clone().get_card_extended_bin());
+ let enable_extended_bin =db
+ .find_config_by_key_unwrap_or(
+ format!("{}_enable_extended_card_bin", profile_id).as_str(),
+ Some("false".to_string()))
+ .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
+
+ let card_extended_bin = match enable_extended_bin {
+ Some(config) if config.config == "true" => {
+ Some(card_data.card_number.clone().get_card_extended_bin())
+ }
+ _ => None,
+ };
let last4 = Some(card_data.card_number.clone().get_last4());
if card_data.card_issuer.is_some()
&& card_data.card_network.is_some()
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 125f79956ac..89c996236a3 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -415,13 +415,23 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.and_then(|pmd| pmd.payment_method_data.clone());
let store = state.clone().store;
+ let profile_id = payment_intent
+ .profile_id
+ .clone()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data_fut = tokio::spawn(
async move {
Ok(n_request_payment_method_data
.async_map(|payment_method_data| async move {
- helpers::get_additional_payment_data(&payment_method_data, store.as_ref())
- .await
+ helpers::get_additional_payment_data(
+ &payment_method_data,
+ store.as_ref(),
+ profile_id.as_ref(),
+ )
+ .await
})
.await)
}
@@ -1059,12 +1069,19 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
.clone();
let payment_token = payment_data.token.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
+ let profile_id = payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_experience = payment_data.payment_attempt.payment_experience;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
- helpers::get_additional_payment_data(payment_method_data, &*state.store).await
+ helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
+ .await
})
.await
.as_ref()
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index aaebccd8802..e770da70747 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -258,7 +258,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.as_ref()
.map(|address| address.address_id.clone()),
attempt_id,
- profile_id,
+ profile_id.clone(),
session_expiry,
)
.await?;
@@ -277,6 +277,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.map(|address| address.address_id.clone()),
&payment_method_info,
merchant_key_store,
+ profile_id,
)
.await?;
@@ -771,6 +772,7 @@ impl PaymentCreate {
payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<PaymentMethod>,
key_store: &domain::MerchantKeyStore,
+ profile_id: String,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
@@ -794,7 +796,12 @@ impl PaymentCreate {
payment_method_data_request.payment_method_data.as_ref()
})
.async_map(|payment_method_data| async {
- helpers::get_additional_payment_data(payment_method_data, &*state.store).await
+ helpers::get_additional_payment_data(
+ payment_method_data,
+ &*state.store,
+ &profile_id,
+ )
+ .await
})
.await;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 804d1dbc800..0aaa6006052 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -593,12 +593,20 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
storage_enums::AttemptStatus::ConfirmationAwaited
}
};
+ let profile_id = payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
- helpers::get_additional_payment_data(payment_method_data, &*state.store).await
+ helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
+ .await
})
.await
.as_ref()
|
2024-04-23T23:14:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add profile level config to toggle the display for the extended card bin in Payment Response .
### 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?
- Create a MA and an MCA
- Make a payment with the toggle for that profile_id as false, as it is default
- In the response the card_bin_extended field will be null
<img width="1049" alt="Screenshot 2024-04-24 at 4 13 09 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/d1dd3166-de79-49fd-8c03-f115125db0a4">
- Now set the toggle for that profile_id as true by hitting the following curl:
```
curl --location 'http://localhost:8080/configs/{profile_id}_enable_extended_card_bin' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{admin_api_key}}' \
--data '{
"key":"{profile_id}_enable_extended_card_bin",
"value":"true"
}'
```
> <img width="1210" alt="Screenshot 2024-05-02 at 1 06 08 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/89341370-de38-4280-a527-72ca8dc13549">
> > The config will also be stored in the database, to check you can run the following query
> ```
> SELECT * FROM configs WHERE key = '{profile_id}_enable_extended_card_bin';
> ```
> <img width="1210" alt="Screenshot 2024-05-02 at 1 07 48 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/c020a3cf-3154-45e6-a079-04a7490a8930">
- Create another payment , now in the Response card_bin_extended field won't be null, as the extended card bin config has been set to true
<img width="1049" alt="Screenshot 2024-04-24 at 4 14 50 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/aab6d569-bfa0-4a3e-bd3b-bebbb3525fbc">
## Checklist
<!-- Put 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
|
5442574c08fcce57bebad2cfbf6547a9b824da58
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4442
|
Bug: Remove duplicated card number interface
### Feature Description
The CardNumber interface has a duplicated method with the same functionality.
### Possible Implementation
Remove one of the duplicated interfaces.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index e045cf2c42d..dd7791ee2d2 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -361,7 +361,7 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {
card_isin: item.card_isin,
card_extended_bin: item
.card_number
- .map(|card_number| card_number.get_card_extended_bin()),
+ .map(|card_number| card_number.get_extended_card_bin()),
card_exp_month: item.expiry_month,
card_exp_year: item.expiry_year,
card_holder_name: item.card_holder_name,
diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs
index 08ad127047c..5a71aaa7863 100644
--- a/crates/cards/src/validate.rs
+++ b/crates/cards/src/validate.rs
@@ -24,7 +24,6 @@ impl CardNumber {
pub fn get_card_isin(self) -> String {
self.0.peek().chars().take(6).collect::<String>()
}
-
pub fn get_extended_card_bin(self) -> String {
self.0.peek().chars().take(8).collect::<String>()
}
@@ -42,9 +41,6 @@ impl CardNumber {
.rev()
.collect::<String>()
}
- pub fn get_card_extended_bin(self) -> String {
- self.0.peek().chars().take(8).collect::<String>()
- }
}
impl FromStr for CardNumber {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 1789c3c3fad..38acf574a7c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3719,7 +3719,7 @@ pub async fn get_additional_payment_data(
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
- Some(card_data.card_number.clone().get_card_extended_bin())
+ Some(card_data.card_number.clone().get_extended_card_bin())
}
_ => None,
};
|
2024-04-21T02:57:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The CardNumber interface has a duplicated method with the same functionality. Removed one.
closes #4442
### 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`
-->
1. crates/cards/src/validate
2. crates/router/src/core/blocklist/utils
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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)?
-->
The methods get_extended_card_bin() and get_card_extended_bin() are identical and thus redundant. It is recommended to keep one and remove the other to avoid confusion.
## 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
|
4b5b558dae8d2fefb66b8b16c486f07e3e800758
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4437
|
Bug: [BUG] Failing unit tests for Routing
### Bug Description
Certain unit tests in the `euclid` and `kgraph_utils` crates are failing.
**euclid**
```
test dssa::analyzer::tests::test_exhaustive_negation_detection ... FAILED
test frontend::dir::test::test_consistent_dir_key_naming ... FAILED
```
**kgraph_utils**
```
test mca::tests::test_sandbox_applepay_bug_usecase ... FAILED
```
### Expected Behavior
All unit tests should pass.
### Actual Behavior
Some tests fail owing to being outdated or due to a code discrepancy.
### Steps To Reproduce
1. Clone the main branch
2. Run the unit tests for the `euclid` and `kgraph_utils` crates
### Context For The Bug
_No response_
### Environment
Local
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/euclid/src/dssa/analyzer.rs b/crates/euclid/src/dssa/analyzer.rs
index 149ed1fd79c..4c615e78495 100644
--- a/crates/euclid/src/dssa/analyzer.rs
+++ b/crates/euclid/src/dssa/analyzer.rs
@@ -304,7 +304,7 @@ mod tests {
& payment_method /= reward
& payment_method /= voucher
& payment_method /= gift_card
-
+ & payment_method /= card_redirect
}
}
}
diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs
index e00d821a310..455330fcf76 100644
--- a/crates/euclid/src/frontend/dir.rs
+++ b/crates/euclid/src/frontend/dir.rs
@@ -306,7 +306,7 @@ pub enum DirKeyKind {
#[serde(rename = "setup_future_usage")]
SetupFutureUsage,
#[strum(
- serialize = "card_redirect_type",
+ serialize = "card_redirect",
detailed_message = "Supported types of Card Redirect payment method",
props(Category = "Payment Method Types")
)]
@@ -559,7 +559,7 @@ impl DirValue {
Self::CardBin(_) => (DirKeyKind::CardBin, None),
Self::RewardType(_) => (DirKeyKind::RewardType, None),
Self::BusinessCountry(_) => (DirKeyKind::BusinessCountry, None),
- Self::BillingCountry(_) => (DirKeyKind::CardBin, None),
+ Self::BillingCountry(_) => (DirKeyKind::BillingCountry, None),
Self::BankTransferType(_) => (DirKeyKind::BankTransferType, None),
Self::UpiType(_) => (DirKeyKind::UpiType, None),
Self::CardType(_) => (DirKeyKind::CardType, None),
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index a04e052514d..8542437a5a6 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -544,6 +544,7 @@ mod tests {
"connector_type": "payment_processor",
"connector_name": "bluesnap",
"merchant_connector_id": "REDACTED",
+ "status": "inactive",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "REDACTED",
@@ -625,6 +626,7 @@ mod tests {
"connector_type": "payment_processor",
"connector_name": "stripe",
"merchant_connector_id": "REDACTED",
+ "status": "inactive",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "REDACTED"
|
2024-04-23T08:53:15Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR fixes failing unit tests for routing, either by updating outdated tests, or resolving code discrepancies. See #4437 for more info on failing tests.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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)?
-->
All unit tests pass locally. Does not require any API 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 the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
589cb4c9f94d6a410627d569aa5495d60ca763ae
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4432
|
Bug: router crate fails to build in WSL unless more memory is added
I am part of a student team hoping to contribute to hyperswitch over the next several months. After following the instructions in `docs/try_local_system.md` for setting up a development environment using WSL, all members of my team encountered the same issue: upon running `cargo build`, the `router` crate failed to build, producing an error ending in `signal: 9, SIGKILL: kill`.
After some research, we came across [this discussion post](https://github.com/juspay/hyperswitch/discussions/758), where the author encountered a similar issue. After trying the suggested solution of configuring WSL to allow an additional 2GB of memory, the issue persisted, however we were able to resolve it by increasing the amount to 24GB.
Some of our machines do not have 24GB of memory, so we ended up editing `.wslconfig` to include 8GB of memory, and then adding an additional 16GB via a swap file created from within the WSL terminal.
Because the same issue occurred for all of us in the exact same way, across different machines, we feel that `docs/try_local_system.md` should mention the issue, along with instructions on how to configure WSL to prevent the issue from occurring.
|
2024-04-23T01:50:08Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This pull request adds a brief note to `docs/try_local_system.md`, under the section titled "Set up dependencies on Windows (Ubuntu on WSL2)," addressing an error that may occur when running `cargo build` from a WSL environment, and providing resources to help the user prevent the issue from occurring.
Additionally, I added a note about this change to `CHANGELOG.md`.
### 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 #4432
## How did you test 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
|
589cb4c9f94d6a410627d569aa5495d60ca763ae
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4427
|
Bug: Blacking token after delete user role
Even after deleting the user role, the logged in user is able to perform the JWT operations. Hence these need to be prohibited by adding the token in blacklist.
|
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 4cce0d3f800..09a0bbfe300 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -70,8 +70,8 @@ impl UserRole {
conn: &PgPooledConn,
user_id: String,
merchant_id: String,
- ) -> StorageResult<bool> {
- generics::generic_delete::<<Self as HasTable>::Table, _>(
+ ) -> StorageResult<Self> {
+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::user_id
.eq(user_id)
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 6ddab570aed..43d6b1c6483 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -282,7 +282,7 @@ pub async fn delete_user_role(
}
};
- if user_roles.len() > 1 {
+ let deleted_user_role = if user_roles.len() > 1 {
state
.store
.delete_user_role_by_user_id_merchant_id(
@@ -291,9 +291,7 @@ pub async fn delete_user_role(
)
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("Error while deleting user role")?;
-
- Ok(ApplicationResponse::StatusOk)
+ .attach_printable("Error while deleting user role")?
} else {
state
.store
@@ -310,8 +308,9 @@ pub async fn delete_user_role(
)
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("Error while deleting user role")?;
+ .attach_printable("Error while deleting user role")?
+ };
- Ok(ApplicationResponse::StatusOk)
- }
+ auth::blacklist::insert_user_in_blacklist(&state, &deleted_user_role.user_id).await?;
+ Ok(ApplicationResponse::StatusOk)
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 73b519e5449..b094d1447e0 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2376,7 +2376,7 @@ impl UserRoleInterface for KafkaStore {
&self,
user_id: &str,
merchant_id: &str,
- ) -> CustomResult<bool, errors::StorageError> {
+ ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store
.delete_user_role_by_user_id_merchant_id(user_id, merchant_id)
.await
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 2f61f70b2a8..e31a2663354 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -48,7 +48,7 @@ pub trait UserRoleInterface {
&self,
user_id: &str,
merchant_id: &str,
- ) -> CustomResult<bool, errors::StorageError>;
+ ) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn list_user_roles_by_user_id(
&self,
@@ -145,8 +145,9 @@ impl UserRoleInterface for Store {
&self,
user_id: &str,
merchant_id: &str,
- ) -> CustomResult<bool, errors::StorageError> {
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
+
storage::UserRole::delete_by_user_id_merchant_id(
&conn,
user_id.to_owned(),
@@ -459,18 +460,19 @@ impl UserRoleInterface for MockDb {
&self,
user_id: &str,
merchant_id: &str,
- ) -> CustomResult<bool, errors::StorageError> {
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut user_roles = self.user_roles.lock().await;
- let user_role_index = user_roles
+
+ match user_roles
.iter()
- .position(|user_role| {
- user_role.user_id == user_id && user_role.merchant_id == merchant_id
- })
- .ok_or(errors::StorageError::ValueNotFound(format!(
- "No user available for user_id = {user_id}"
- )))?;
- user_roles.remove(user_role_index);
- Ok(true)
+ .position(|role| role.user_id == user_id && role.merchant_id == merchant_id)
+ {
+ Some(index) => Ok(user_roles.remove(index)),
+ None => Err(errors::StorageError::ValueNotFound(
+ "Cannot find user role to delete".to_string(),
+ )
+ .into()),
+ }
}
async fn list_user_roles_by_user_id(
@@ -521,7 +523,7 @@ impl UserRoleInterface for super::KafkaStore {
&self,
user_id: &str,
merchant_id: &str,
- ) -> CustomResult<bool, errors::StorageError> {
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
.delete_user_role_by_user_id_merchant_id(user_id, merchant_id)
.await
|
2024-04-22T14:07:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The PR add support to blocklist JWT token of the deleted user/user role. After delete signined user won't be able to perform any operation as token is blocklisted.
### 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 #4427
## How did you test it?
SignIn/Signup
```
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"email": "test1@gmail.com",
"password": "t"
}'
```
Invite another user
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"email": "test3@gmail.com",
"name": "test3",
"role_id": "merchant_view_only"
}'
```
Sign in to this new user account and perform some operations JWT based, like listing payments etc.
Sing in again into account from which this user was invited.
Delete this new user
```
curl --location --request DELETE 'http://localhost:8080/user/user/delete' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"email": "test3@gmail.com"
}'
```
Response 200 Ok
Try performing same operations for the newly invited user now, it should give response:
```
{
"error": {
"type": "invalid_request",
"message": "Access forbidden, invalid JWT token was used",
"code": "IR_17"
}
}
```
This means the previous token is blacklisted sucessfully.
## Checklist
<!-- Put an `x` in 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
|
447655382bcf2fdd69a1ec6a56e5e4df8a8feef2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4424
|
Bug: [REFACTOR] store `card_network` in locker
We have `card_brand` field in locker which is `None` currently for all cards. When a `card_network` is sent in the request, map it to `card_brand` and store it in locker.
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 25bb869075c..fb8444f515b 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1167,7 +1167,7 @@ pub async fn add_card_hs(
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.card_exp_month.to_owned(),
card_exp_year: card.card_exp_year.to_owned(),
- card_brand: None,
+ card_brand: card.card_network.as_ref().map(ToString::to_string),
card_isin: None,
nick_name: card.nick_name.as_ref().map(masking::Secret::peek).cloned(),
},
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index de2fdd99b7b..65f49237e7c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1,4 +1,4 @@
-use std::borrow::Cow;
+use std::{borrow::Cow, str::FromStr};
use api_models::{
mandates::RecurringDetails,
@@ -1780,9 +1780,17 @@ pub async fn retrieve_card_with_permanent_token(
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
- card_issuer: card.card_brand,
+ card_issuer: None,
nick_name: card.nick_name.map(masking::Secret::new),
- card_network: None,
+ card_network: card
+ .card_brand
+ .map(|card_brand| enums::CardNetwork::from_str(&card_brand))
+ .transpose()
+ .map_err(|e| {
+ logger::error!("Failed to parse card network {}", e);
+ })
+ .ok()
+ .flatten(),
card_type: None,
card_issuing_country: None,
bank_code: None,
|
2024-04-22T11:57: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 -->
We have `card_brand` field in locker which is `None` currently for all cards. When a `card_network` is sent in the request, we map it to `card_brand` and store it in locker.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Store a payment method in locker with `card_network` field in request.
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4111111111111111",
"card_exp_month": "04",
"card_exp_year": "25",
"card_holder_name": "John",
"card_network": "Visa"
},
"customer_id": "cus_spLo0JPwK16PTtBuIk1b",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Retrieve stored card with `list_customer_payment_methods` and verify whether card_network is populated.
## Checklist
<!-- Put an `x` in 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
|
b8be10de52e40d2327819d33c6c1ec40a459bdd5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4421
|
Bug: Accepting merchant public key and ttl for encrypting payload
Collect `public_key` and `raw_card_ttl` and store it in `business_profile` table. Use update endpoint to achieve this
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index cfc9694dda3..d4d1b3d80b9 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1042,6 +1042,9 @@ pub struct BusinessProfileUpdate {
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
+
+ /// Merchant's config to support extended card info feature
+ pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
@@ -1095,3 +1098,9 @@ pub struct ExtendedCardInfoChoice {
}
impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ExtendedCardInfoConfig {
+ pub public_key: Secret<String>,
+ pub ttl_in_secs: u16,
+}
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 7911aa403d6..90a9dcbb7d8 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -36,6 +36,7 @@ pub struct BusinessProfile {
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<serde_json::Value>,
pub is_extended_card_info_enabled: Option<bool>,
+ pub extended_card_info_config: Option<pii::SecretSerdeValue>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -63,6 +64,7 @@ pub struct BusinessProfileNew {
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<serde_json::Value>,
pub is_extended_card_info_enabled: Option<bool>,
+ pub extended_card_info_config: Option<pii::SecretSerdeValue>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -87,6 +89,7 @@ pub struct BusinessProfileUpdateInternal {
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<serde_json::Value>,
pub is_extended_card_info_enabled: Option<bool>,
+ pub extended_card_info_config: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -109,6 +112,7 @@ pub enum BusinessProfileUpdate {
payment_link_config: Option<serde_json::Value>,
session_expiry: Option<i64>,
authentication_connector_details: Option<serde_json::Value>,
+ extended_card_info_config: Option<pii::SecretSerdeValue>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
@@ -136,6 +140,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
payment_link_config,
session_expiry,
authentication_connector_details,
+ extended_card_info_config,
} => Self {
profile_name,
modified_at,
@@ -154,6 +159,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
payment_link_config,
session_expiry,
authentication_connector_details,
+ extended_card_info_config,
..Default::default()
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
@@ -190,6 +196,7 @@ impl From<BusinessProfileNew> for BusinessProfile {
session_expiry: new.session_expiry,
authentication_connector_details: new.authentication_connector_details,
is_extended_card_info_enabled: new.is_extended_card_info_enabled,
+ extended_card_info_config: new.extended_card_info_config,
}
}
}
@@ -215,6 +222,7 @@ impl BusinessProfileUpdate {
session_expiry,
authentication_connector_details,
is_extended_card_info_enabled,
+ extended_card_info_config,
} = self.into();
BusinessProfile {
profile_name: profile_name.unwrap_or(source.profile_name),
@@ -237,6 +245,7 @@ impl BusinessProfileUpdate {
session_expiry,
authentication_connector_details,
is_extended_card_info_enabled,
+ extended_card_info_config,
..source
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index c4277a5cc7a..e284e780d2e 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -194,6 +194,7 @@ diesel::table! {
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
+ extended_card_info_config -> Nullable<Jsonb>,
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 3c6ab1f31d6..eab7ea6a7ed 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -439,6 +439,7 @@ pub async fn update_business_profile_cascade(
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
+ extended_card_info_config: None,
};
let update_futures = business_profiles.iter().map(|business_profile| async {
@@ -1648,6 +1649,19 @@ pub async fn update_business_profile(
})
.transpose()?;
+ let extended_card_info_config = request
+ .extended_card_info_config
+ .as_ref()
+ .map(|config| {
+ config
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "extended_card_info_config",
+ })
+ })
+ .transpose()?
+ .map(Secret::new);
+
let business_profile_update = storage::business_profile::BusinessProfileUpdate::Update {
profile_name: request.profile_name,
modified_at: Some(date_time::now()),
@@ -1676,6 +1690,7 @@ pub async fn update_business_profile(
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "authentication_connector_details",
})?,
+ extended_card_info_config,
};
let updated_business_profile = db
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 62925dcc2a5..fb86ba5a87b 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -263,6 +263,7 @@ pub async fn update_business_profile_active_algorithm_ref(
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
+ extended_card_info_config: None,
};
db.update_business_profile_by_profile_id(current_business_profile, business_profile_update)
.await
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 06935a29fb3..77fe8371817 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -176,6 +176,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
field_name: "authentication_connector_details",
})?,
is_extended_card_info_enabled: None,
+ extended_card_info_config: None,
})
}
}
diff --git a/migrations/2024-04-24-075735_add-merchant-pkey-ttl-to-business-profile/down.sql b/migrations/2024-04-24-075735_add-merchant-pkey-ttl-to-business-profile/down.sql
new file mode 100644
index 00000000000..63a07052cbe
--- /dev/null
+++ b/migrations/2024-04-24-075735_add-merchant-pkey-ttl-to-business-profile/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE business_profile DROP COLUMN IF EXISTS extended_card_info_config;
\ No newline at end of file
diff --git a/migrations/2024-04-24-075735_add-merchant-pkey-ttl-to-business-profile/up.sql b/migrations/2024-04-24-075735_add-merchant-pkey-ttl-to-business-profile/up.sql
new file mode 100644
index 00000000000..f1b9ca58f84
--- /dev/null
+++ b/migrations/2024-04-24-075735_add-merchant-pkey-ttl-to-business-profile/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS extended_card_info_config JSONB DEFAULT NULL;
\ No newline at end of file
|
2024-04-24T16:14: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 -->
This PR adds support for merchant to pass his public key as well as ttl using update endpoint of business profile. The config passed is stored in business profile table as JSONB.
### 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)?
-->
1. Create a business profile for a merchant (Default one which gets created during merchant account creation works too)
2. Use update endpoint of business profile to pass config.
```
curl --location 'http://localhost:8080/account/:merchant_id/business_profile/:profile_id' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"extended_card_info_config": {
"public_key": "pub_key_1",
"ttl_in_secs": 60
}
}'
```

3. For verifying, u could check the db if the config is stored in `extended_card_info_config` column in `business_profile` table using below query
```
SELECT extended_card_info_config FROM business_profile WHERE profile_id = 'profile_id';
```
## Checklist
<!-- Put an `x` in 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
|
c20ecb855aa3c4b3ce1798dcc19910fb38345b46
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4415
|
Bug: cookie implementation
|
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 5203b20c55b..03db3987eaa 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -611,19 +611,17 @@ where
T: serde::de::DeserializeOwned,
A: AppStateInfo + Sync,
{
- let token = get_jwt_from_authorization_header(headers)?;
- if let Some(token_from_cookies) = get_cookie_from_header(headers)
- .ok()
- .and_then(|cookies| cookies::parse_cookie(cookies).ok())
- {
- logger::info!(
- "Cookie header and authorization header JWT comparison result: {}",
- token == token_from_cookies
- );
- }
- let payload = decode_jwt(token, state).await?;
-
- Ok(payload)
+ let token = match get_cookie_from_header(headers).and_then(cookies::parse_cookie) {
+ Ok(cookies) => cookies,
+ Err(e) => {
+ let token = get_jwt_from_authorization_header(headers);
+ if token.is_err() {
+ logger::error!(?e);
+ }
+ token?.to_owned()
+ }
+ };
+ decode_jwt(&token, state).await
}
#[async_trait]
@@ -949,6 +947,9 @@ pub async fn is_ephemeral_auth<A: AppStateInfo + Sync>(
pub fn is_jwt_auth(headers: &HeaderMap) -> bool {
headers.get(crate::headers::AUTHORIZATION).is_some()
+ || get_cookie_from_header(headers)
+ .and_then(cookies::parse_cookie)
+ .is_ok()
}
pub async fn decode_jwt<T>(token: &str, state: &impl AppStateInfo) -> RouterResult<T>
|
2024-04-23T07:52:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Use cookie if present otherwise use `authorization` header for authentication.
<!-- 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
Use of cookie for authentication for better security.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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?
Use any JWT auth API with cookies.
If cookie is present with `login_token` then app will use it for auth otherwise it will fallback to use `Authorization` header.
Example curl,
```curl
curl --location '<URL>/user/permission_info?groups=true' \
--header 'Cookie: login_token=<JWT>'
```
Above should give `200` when valid JWT is used.
```curl
curl --location 'localhost:8080/user/permission_info?groups=true' \
--header 'Authorization: Bearer <JWT>' \
```
Above should also give `200` when valid JWT is used.
<!--
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
|
589cb4c9f94d6a410627d569aa5495d60ca763ae
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4412
|
Bug: BE Password specification
Make password have
Minimum number of characters.
At least one number, uppercase & lowercase characters and symbol. (This check is there in FE but not in BE).
|
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 1cda969f780..f14610649f4 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,3 +1,5 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
+pub const MAX_PASSWORD_LENGTH: usize = 70;
+pub const MIN_PASSWORD_LENGTH: usize = 8;
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index fab02df88ba..0b971d82032 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -155,7 +155,32 @@ pub struct UserPassword(Secret<String>);
impl UserPassword {
pub fn new(password: Secret<String>) -> UserResult<Self> {
let password = password.expose();
- if password.is_empty() {
+
+ let mut has_upper_case = false;
+ let mut has_lower_case = false;
+ let mut has_numeric_value = false;
+ let mut has_special_character = false;
+ let mut has_whitespace = false;
+
+ for c in password.chars() {
+ has_upper_case = has_upper_case || c.is_uppercase();
+ has_lower_case = has_lower_case || c.is_lowercase();
+ has_numeric_value = has_numeric_value || c.is_numeric();
+ has_special_character =
+ has_special_character || !(c.is_alphanumeric() && c.is_whitespace());
+ has_whitespace = has_whitespace || c.is_whitespace();
+ }
+
+ let is_password_format_valid = has_upper_case
+ && has_lower_case
+ && has_numeric_value
+ && has_special_character
+ && !has_whitespace;
+
+ let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH;
+ let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH;
+
+ if is_too_short || is_too_long || !is_password_format_valid {
Err(UserErrors::PasswordParsingError.into())
} else {
Ok(Self(password.into()))
|
2024-04-29T11:12:01Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Closes #4412
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
The mandatory condition for the password field was just not be empty . Following the PR, the password field will be subject to the following checks:
1.The password must be between 8 and 50 characters in length.
2.It must include at least one uppercase character.
3.It must include at least one lowercase character.
4.It must include at least one special character.
5.It must include at least one numeric character.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Signup API ( local testing)
```
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email value",
"password": "456667sdvh",
"country": "IN"
}'
```
Failure case response
```
{
"error": {
"type": "invalid_request",
"message": "Invalid Password",
"code": "UR_09"
}
}
```
2. Reset Password API (local testing)
```
curl --location 'http://localhost:8080/user/reset_password' \
--header 'Content-Type: application/json' \
--data '{
"password": "456667sdvd",
"token":"token from email after clicking Reset password in dashboard"
}'
```
Failure case response
```
{
"error": {
"type": "invalid_request",
"message": "Invalid Password",
"code": "UR_09"
}
}
```
## Checklist
<!-- Put an `x` in 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
|
86e93cd3a0f050c89a82be409b80dc2894143c9e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4411
|
Bug: Force password reset
- Force user to change the password after certain amount of time.
- Force user to set password after user lands to dashboard without setting his/her password (invite flow).
|
diff --git a/config/config.example.toml b/config/config.example.toml
index f0dad483c65..c9fb0f34740 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -345,6 +345,9 @@ active_email_client = "SES" # The currently active email client
email_role_arn = "" # The amazon resource name ( arn ) of the role which has permission to send emails
sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
+[user]
+password_validity_in_days = 90 # Number of days after which password should be updated
+
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index faf3bb7f466..7596fd5cd6b 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -108,6 +108,9 @@ refund_tolerance = 100 # Fake d
refund_ttl = 172800 # Time to live for dummy connector refund in redis
slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg" # Slack invite url for hyperswitch
+[user]
+password_validity_in_days = 90
+
[frm]
enabled = true
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index f564b976bc0..747bb269a18 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -115,6 +115,9 @@ refund_tolerance = 100 # Fake d
refund_ttl = 172800 # Time to live for dummy connector refund in redis
slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg" # Slack invite url for hyperswitch
+[user]
+password_validity_in_days = 90
+
[frm]
enabled = false
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 35c8a2ba3d6..fb669dfbdb8 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -115,6 +115,9 @@ refund_tolerance = 100 # Fake d
refund_ttl = 172800 # Time to live for dummy connector refund in redis
slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg" # Slack invite url for hyperswitch
+[user]
+password_validity_in_days = 90
+
[frm]
enabled = true
diff --git a/config/development.toml b/config/development.toml
index 3f05872bc6a..a7b7f4000ea 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -261,6 +261,9 @@ active_email_client = "SES"
email_role_arn = ""
sts_role_session_name = ""
+[user]
+password_validity_in_days = 90
+
[bank_config.eps]
stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 9fd22f46707..f11c2e19045 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -51,6 +51,9 @@ jwt_secret = "secret"
master_enc_key = "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e13a"
recon_admin_api_key = "recon_test_admin"
+[user]
+password_validity_in_days = 90
+
[locker]
host = ""
host_rs = ""
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index b29b28f0136..dab9ace3ac2 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -14,8 +14,8 @@ use crate::user::{
CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
- SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
- SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
+ RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest,
+ SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
};
@@ -60,6 +60,7 @@ common_utils::impl_misc_api_event_type!(
ConnectAccountRequest,
ForgotPasswordRequest,
ResetPasswordRequest,
+ RotatePasswordRequest,
InviteUserRequest,
ReInviteUserRequest,
VerifyEmailRequest,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index fe4e37f8a8c..b2128cc949c 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -91,6 +91,11 @@ pub struct ResetPasswordRequest {
pub password: Secret<String>,
}
+#[derive(serde::Deserialize, Debug, serde::Serialize)]
+pub struct RotatePasswordRequest {
+ pub password: Secret<String>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct InviteUserRequest {
pub email: pii::Email,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3c86064731b..96e91f0c738 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2716,6 +2716,7 @@ pub enum TokenPurpose {
TOTP,
VerifyEmail,
AcceptInvitationFromEmail,
+ ForceSetPassword,
ResetPassword,
AcceptInvite,
UserInfo,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 2e28bc5d30f..810d82d321f 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1191,6 +1191,7 @@ diesel::table! {
last_modified_at -> Timestamp,
#[max_length = 64]
preferred_merchant_id -> Nullable<Varchar>,
+ last_password_modified_at -> Nullable<Timestamp>,
}
}
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 84fe8710060..850619f8af6 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -20,6 +20,7 @@ pub struct User {
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub preferred_merchant_id: Option<String>,
+ pub last_password_modified_at: Option<PrimitiveDateTime>,
}
#[derive(
@@ -35,6 +36,7 @@ pub struct UserNew {
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
pub preferred_merchant_id: Option<String>,
+ pub last_password_modified_at: Option<PrimitiveDateTime>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
@@ -45,6 +47,7 @@ pub struct UserUpdateInternal {
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
preferred_merchant_id: Option<String>,
+ last_password_modified_at: Option<PrimitiveDateTime>,
}
#[derive(Debug)]
@@ -52,10 +55,12 @@ pub enum UserUpdate {
VerifyUser,
AccountUpdate {
name: Option<String>,
- password: Option<Secret<String>>,
is_verified: Option<bool>,
preferred_merchant_id: Option<String>,
},
+ PasswordUpdate {
+ password: Option<Secret<String>>,
+ },
}
impl From<UserUpdate> for UserUpdateInternal {
@@ -68,18 +73,27 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified: Some(true),
last_modified_at,
preferred_merchant_id: None,
+ last_password_modified_at: None,
},
UserUpdate::AccountUpdate {
name,
- password,
is_verified,
preferred_merchant_id,
} => Self {
name,
- password,
+ password: None,
is_verified,
last_modified_at,
preferred_merchant_id,
+ last_password_modified_at: None,
+ },
+ UserUpdate::PasswordUpdate { password } => Self {
+ name: None,
+ password,
+ is_verified: None,
+ last_modified_at,
+ preferred_merchant_id: None,
+ last_password_modified_at: Some(last_modified_at),
},
}
}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 423f8e03d23..dc8b5dd6bd5 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -334,6 +334,7 @@ pub(crate) async fn fetch_raw_secrets(
dummy_connector: conf.dummy_connector,
#[cfg(feature = "email")]
email: conf.email,
+ user: conf.user,
mandates: conf.mandates,
network_transaction_id_supported_connectors: conf
.network_transaction_id_supported_connectors,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index adc09fb55af..5d2077b8829 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -89,6 +89,7 @@ pub struct Settings<S: SecretState> {
pub dummy_connector: DummyConnector,
#[cfg(feature = "email")]
pub email: EmailSettings,
+ pub user: UserSettings,
pub cors: CorsSettings,
pub mandates: Mandates,
pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors,
@@ -392,6 +393,11 @@ pub struct Secrets {
pub master_enc_key: Secret<String>,
}
+#[derive(Debug, Clone, Default, Deserialize)]
+pub struct UserSettings {
+ pub password_validity_in_days: u16,
+}
+
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Locker {
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 8a7d77cdbc9..ddcd10c32e4 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -198,7 +198,7 @@ impl UserErrors {
Self::IpAddressParsingFailed => "Something went wrong",
Self::InvalidMetadataRequest => "Invalid Metadata Request",
Self::MerchantIdParsingError => "Invalid Merchant Id",
- Self::ChangePasswordError => "Old and new password cannot be the same",
+ Self::ChangePasswordError => "Old and new password cannot be same",
Self::InvalidDeleteOperation => "Delete Operation Not Supported",
Self::MaxInvitationsError => "Maximum invite count per request exceeded",
Self::RoleNotFound => "Role Not Found",
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 6ad0afa9104..e51ad6120c9 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -349,11 +349,8 @@ pub async fn change_password(
.store
.update_user_by_user_id(
user.get_user_id(),
- diesel_models::user::UserUpdate::AccountUpdate {
- name: None,
+ diesel_models::user::UserUpdate::PasswordUpdate {
password: Some(new_password_hash),
- is_verified: None,
- preferred_merchant_id: None,
},
)
.await
@@ -419,9 +416,48 @@ pub async fn forgot_password(
Ok(ApplicationResponse::StatusOk)
}
+pub async fn rotate_password(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ request: user_api::RotatePasswordRequest,
+ _req_state: ReqState,
+) -> UserResponse<()> {
+ let user: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ let password = domain::UserPassword::new(request.password.to_owned())?;
+ let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
+
+ if user.compare_password(request.password).is_ok() {
+ return Err(UserErrors::ChangePasswordError.into());
+ }
+
+ let user = state
+ .store
+ .update_user_by_user_id(
+ &user_token.user_id,
+ storage_user::UserUpdate::PasswordUpdate {
+ password: Some(hash_password),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
+ .await
+ .map_err(|e| logger::error!(?e));
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
#[cfg(feature = "email")]
-pub async fn reset_password(
+pub async fn reset_password_token_only_flow(
state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
request: user_api::ResetPasswordRequest,
) -> UserResponse<()> {
let token = request.token.expose();
@@ -431,8 +467,60 @@ pub async fn reset_password(
auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_email(
+ &email_token
+ .get_email()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if user_from_db.get_user_id() != user_token.user_id {
+ return Err(UserErrors::LinkInvalid.into());
+ }
+
let password = domain::UserPassword::new(request.password)?;
+ let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
+
+ let user = state
+ .store
+ .update_user_by_email(
+ &email_token
+ .get_email()
+ .change_context(UserErrors::InternalServerError)?,
+ storage_user::UserUpdate::PasswordUpdate {
+ password: Some(hash_password),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+ let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
+ .await
+ .map_err(|e| logger::error!(?e));
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
+#[cfg(feature = "email")]
+pub async fn reset_password(
+ state: AppState,
+ request: user_api::ResetPasswordRequest,
+) -> UserResponse<()> {
+ let token = request.token.expose();
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
+ .await
+ .change_context(UserErrors::LinkInvalid)?;
+
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+
+ let password = domain::UserPassword::new(request.password)?;
let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
let user = state
@@ -441,11 +529,8 @@ pub async fn reset_password(
&email_token
.get_email()
.change_context(UserErrors::InternalServerError)?,
- storage_user::UserUpdate::AccountUpdate {
- name: None,
+ storage_user::UserUpdate::PasswordUpdate {
password: Some(hash_password),
- is_verified: Some(true),
- preferred_merchant_id: None,
},
)
.await
@@ -1449,7 +1534,6 @@ pub async fn update_user_details(
let user_update = storage_user::UserUpdate::AccountUpdate {
name: name.map(|x| x.get_secret().expose()),
- password: None,
is_verified: None,
preferred_merchant_id: req.preferred_merchant_id,
};
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index 47b3d376a16..9ec7cf6fab4 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -162,6 +162,7 @@ impl UserInterface for MockDb {
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
preferred_merchant_id: user_data.preferred_merchant_id,
+ last_password_modified_at: user_data.last_password_modified_at,
};
users.push(user.clone());
Ok(user)
@@ -218,18 +219,21 @@ impl UserInterface for MockDb {
},
storage::UserUpdate::AccountUpdate {
name,
- password,
is_verified,
preferred_merchant_id,
} => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
- password: password.clone().unwrap_or(user.password.clone()),
is_verified: is_verified.unwrap_or(user.is_verified),
preferred_merchant_id: preferred_merchant_id
.clone()
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::PasswordUpdate { password } => storage::User {
+ password: password.clone().unwrap_or(user.password.clone()),
+ last_password_modified_at: Some(common_utils::date_time::now()),
+ ..user.to_owned()
+ },
};
user.to_owned()
})
@@ -258,18 +262,21 @@ impl UserInterface for MockDb {
},
storage::UserUpdate::AccountUpdate {
name,
- password,
is_verified,
preferred_merchant_id,
} => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
- password: password.clone().unwrap_or(user.password.clone()),
is_verified: is_verified.unwrap_or(user.is_verified),
preferred_merchant_id: preferred_merchant_id
.clone()
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::PasswordUpdate { password } => storage::User {
+ password: password.clone().unwrap_or(user.password.clone()),
+ last_password_modified_at: Some(common_utils::date_time::now()),
+ ..user.to_owned()
+ },
};
user.to_owned()
})
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 6a8a4ee5e03..b7b2e8a2d70 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1184,6 +1184,7 @@ impl User {
.service(web::resource("").route(web::get().to(get_user_details)))
.service(web::resource("/v2/signin").route(web::post().to(user_signin)))
.service(web::resource("/signout").route(web::post().to(signout)))
+ .service(web::resource("/rotate_password").route(web::post().to(rotate_password)))
.service(web::resource("/change_password").route(web::post().to(change_password)))
.service(web::resource("/internal_signup").route(web::post().to(internal_user_signup)))
.service(web::resource("/switch_merchant").route(web::post().to(switch_merchant_id)))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index bf91f8055d1..a308c3e8908 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -203,6 +203,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListUsersForMerchantAccount
| Flow::ForgotPassword
| Flow::ResetPassword
+ | Flow::RotatePassword
| Flow::InviteMultipleUser
| Flow::ReInviteUser
| Flow::UserSignUpWithMerchantId
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index a3f18168501..da444559084 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -5,6 +5,7 @@ use api_models::{
errors::types::ApiErrorResponse,
user::{self as user_api},
};
+use common_enums::TokenPurpose;
use common_utils::errors::ReportSwitchExt;
use router_env::Flow;
@@ -357,43 +358,78 @@ pub async fn list_users_for_merchant_account(
.await
}
-#[cfg(feature = "email")]
-pub async fn forgot_password(
+pub async fn rotate_password(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Json<user_api::ForgotPasswordRequest>,
+ payload: web::Json<user_api::RotatePasswordRequest>,
) -> HttpResponse {
- let flow = Flow::ForgotPassword;
+ let flow = Flow::RotatePassword;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
- |state, _, payload, _| user_core::forgot_password(state, payload),
- &auth::NoAuth,
+ user_core::rotate_password,
+ &auth::SinglePurposeJWTAuth(TokenPurpose::ForceSetPassword),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "email")]
-pub async fn reset_password(
+pub async fn forgot_password(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Json<user_api::ResetPasswordRequest>,
+ payload: web::Json<user_api::ForgotPasswordRequest>,
) -> HttpResponse {
- let flow = Flow::ResetPassword;
+ let flow = Flow::ForgotPassword;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
- |state, _, payload, _| user_core::reset_password(state, payload),
+ |state, _, payload, _| user_core::forgot_password(state, payload),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
+
+#[cfg(feature = "email")]
+pub async fn reset_password(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Json<user_api::ResetPasswordRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
+) -> HttpResponse {
+ let flow = Flow::ResetPassword;
+ let is_token_only = query.into_inner().token_only;
+ if let Some(true) = is_token_only {
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload.into_inner(),
+ |state, user, payload, _| {
+ user_core::reset_password_token_only_flow(state, user, payload)
+ },
+ &auth::SinglePurposeJWTAuth(TokenPurpose::ResetPassword),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ } else {
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload.into_inner(),
+ |state, _, payload, _| user_core::reset_password(state, payload),
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+}
pub async fn invite_multiple_user(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index b4b5df2f46c..882a3ab0d14 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -774,6 +774,26 @@ impl UserFromStorage {
Ok(Some(days_left_for_verification.whole_days()))
}
+ pub fn is_password_rotate_required(&self, state: &AppState) -> UserResult<bool> {
+ let last_password_modified_at =
+ if let Some(last_password_modified_at) = self.0.last_password_modified_at {
+ last_password_modified_at.date()
+ } else {
+ return Ok(true);
+ };
+
+ let password_change_duration =
+ time::Duration::days(state.conf.user.password_validity_in_days.into());
+ let last_date_for_password_rotate = last_password_modified_at
+ .checked_add(password_change_duration)
+ .ok_or(UserErrors::InternalServerError)?;
+
+ let today = common_utils::date_time::now().date();
+ let days_left_for_password_rotate = last_date_for_password_rotate - today;
+
+ Ok(days_left_for_password_rotate.whole_days() < 0)
+ }
+
pub fn get_preferred_merchant_id(&self) -> Option<String> {
self.0.preferred_merchant_id.clone()
}
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index 616c595b244..d635ac064fe 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -44,8 +44,7 @@ impl SPTFlow {
Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
Self::VerifyEmail => Ok(user.0.is_verified),
// Final Checks
- // TODO: this should be based on last_password_modified_at as a placeholder using false
- Self::ForceSetPassword => Ok(false),
+ Self::ForceSetPassword => user.is_password_rotate_required(state),
Self::MerchantSelect => user
.get_roles_from_db(state)
.await
@@ -159,8 +158,9 @@ const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 5] = [
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
-const RESET_PASSWORD_FLOW: [UserFlow; 2] = [
+const RESET_PASSWORD_FLOW: [UserFlow; 3] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
+ UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ResetPassword),
];
@@ -286,7 +286,8 @@ impl From<SPTFlow> for TokenPurpose {
SPTFlow::VerifyEmail => Self::VerifyEmail,
SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
SPTFlow::MerchantSelect => Self::AcceptInvite,
- SPTFlow::ResetPassword | SPTFlow::ForceSetPassword => Self::ResetPassword,
+ SPTFlow::ResetPassword => Self::ResetPassword,
+ SPTFlow::ForceSetPassword => Self::ForceSetPassword,
}
}
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index e8ffe0685b2..e2b621e2132 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -362,6 +362,8 @@ pub enum Flow {
ForgotPassword,
/// Reset password using link
ResetPassword,
+ /// Force set or force change password
+ RotatePassword,
/// Invite multiple users
InviteMultipleUser,
/// Reinvite user
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 799582c733f..73136a191cd 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -28,6 +28,9 @@ host = "redis-queue"
admin_api_key = "test_admin"
jwt_secret = "secret"
+[user]
+password_validity_in_days = 90
+
[locker]
host = ""
host_rs = ""
diff --git a/migrations/2024-05-07-092445_add_last_password_modified_at_column_to_users/down.sql b/migrations/2024-05-07-092445_add_last_password_modified_at_column_to_users/down.sql
new file mode 100644
index 00000000000..89253d525ce
--- /dev/null
+++ b/migrations/2024-05-07-092445_add_last_password_modified_at_column_to_users/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users DROP COLUMN IF EXISTS last_password_modified_at;
\ No newline at end of file
diff --git a/migrations/2024-05-07-092445_add_last_password_modified_at_column_to_users/up.sql b/migrations/2024-05-07-092445_add_last_password_modified_at_column_to_users/up.sql
new file mode 100644
index 00000000000..d5846b0fad4
--- /dev/null
+++ b/migrations/2024-05-07-092445_add_last_password_modified_at_column_to_users/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE users ADD COLUMN IF NOT EXISTS last_password_modified_at TIMESTAMP;
\ No newline at end of file
|
2024-05-06T19:48:55Z
|
## 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
- Allow users to set password when newly signing in
- Allow users to force change password after specified duration of time
### 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
Closes [#4411](https://github.com/juspay/hyperswitch/issues/4411)
## How did you test it?
Use the curl:
```
curl --location 'http://localhost:8080/user/rotate_password' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"password": "new_password"
}'
```
Response will 200 Ok for all successful password change.
If current password and new password is same then response will be Invalid password error.
## Checklist
<!-- Put an `x` in 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
|
5ec00d96de49ae0e0f76c5b19e22db11e7db6dd2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4420
|
Bug: System config for enabling this feature for a specific merchant (by business profile)
Adding a feature flag at business profile level to enable raw card forwarding.
Feature flag to be set using /profile/:id:/extended_card_info with auth as admin api key
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 88d584b6a71..cfc9694dda3 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1088,3 +1088,10 @@ pub struct PaymentLinkConfig {
/// Enable saved payment method option for payment link
pub enabled_saved_payment_method: bool,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
+pub struct ExtendedCardInfoChoice {
+ pub enabled: bool,
+}
+
+impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {}
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index d5d4f5d805f..7911aa403d6 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -35,6 +35,7 @@ pub struct BusinessProfile {
pub payment_link_config: Option<serde_json::Value>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<serde_json::Value>,
+ pub is_extended_card_info_enabled: Option<bool>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -61,6 +62,7 @@ pub struct BusinessProfileNew {
pub payment_link_config: Option<serde_json::Value>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<serde_json::Value>,
+ pub is_extended_card_info_enabled: Option<bool>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -84,6 +86,84 @@ pub struct BusinessProfileUpdateInternal {
pub payment_link_config: Option<serde_json::Value>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<serde_json::Value>,
+ pub is_extended_card_info_enabled: Option<bool>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub enum BusinessProfileUpdate {
+ Update {
+ profile_name: Option<String>,
+ modified_at: Option<time::PrimitiveDateTime>,
+ return_url: Option<String>,
+ enable_payment_response_hash: Option<bool>,
+ payment_response_hash_key: Option<String>,
+ redirect_to_merchant_with_http_post: Option<bool>,
+ webhook_details: Option<serde_json::Value>,
+ metadata: Option<pii::SecretSerdeValue>,
+ routing_algorithm: Option<serde_json::Value>,
+ intent_fulfillment_time: Option<i64>,
+ frm_routing_algorithm: Option<serde_json::Value>,
+ payout_routing_algorithm: Option<serde_json::Value>,
+ is_recon_enabled: Option<bool>,
+ applepay_verified_domains: Option<Vec<String>>,
+ payment_link_config: Option<serde_json::Value>,
+ session_expiry: Option<i64>,
+ authentication_connector_details: Option<serde_json::Value>,
+ },
+ ExtendedCardInfoUpdate {
+ is_extended_card_info_enabled: Option<bool>,
+ },
+}
+
+impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
+ fn from(business_profile_update: BusinessProfileUpdate) -> Self {
+ match business_profile_update {
+ BusinessProfileUpdate::Update {
+ profile_name,
+ modified_at,
+ return_url,
+ enable_payment_response_hash,
+ payment_response_hash_key,
+ redirect_to_merchant_with_http_post,
+ webhook_details,
+ metadata,
+ routing_algorithm,
+ intent_fulfillment_time,
+ frm_routing_algorithm,
+ payout_routing_algorithm,
+ is_recon_enabled,
+ applepay_verified_domains,
+ payment_link_config,
+ session_expiry,
+ authentication_connector_details,
+ } => Self {
+ profile_name,
+ modified_at,
+ return_url,
+ enable_payment_response_hash,
+ payment_response_hash_key,
+ redirect_to_merchant_with_http_post,
+ webhook_details,
+ metadata,
+ routing_algorithm,
+ intent_fulfillment_time,
+ frm_routing_algorithm,
+ payout_routing_algorithm,
+ is_recon_enabled,
+ applepay_verified_domains,
+ payment_link_config,
+ session_expiry,
+ authentication_connector_details,
+ ..Default::default()
+ },
+ BusinessProfileUpdate::ExtendedCardInfoUpdate {
+ is_extended_card_info_enabled,
+ } => Self {
+ is_extended_card_info_enabled,
+ ..Default::default()
+ },
+ }
+ }
}
impl From<BusinessProfileNew> for BusinessProfile {
@@ -109,13 +189,14 @@ impl From<BusinessProfileNew> for BusinessProfile {
payment_link_config: new.payment_link_config,
session_expiry: new.session_expiry,
authentication_connector_details: new.authentication_connector_details,
+ is_extended_card_info_enabled: new.is_extended_card_info_enabled,
}
}
}
-impl BusinessProfileUpdateInternal {
+impl BusinessProfileUpdate {
pub fn apply_changeset(self, source: BusinessProfile) -> BusinessProfile {
- let Self {
+ let BusinessProfileUpdateInternal {
profile_name,
modified_at: _,
return_url,
@@ -133,7 +214,8 @@ impl BusinessProfileUpdateInternal {
payment_link_config,
session_expiry,
authentication_connector_details,
- } = self;
+ is_extended_card_info_enabled,
+ } = self.into();
BusinessProfile {
profile_name: profile_name.unwrap_or(source.profile_name),
modified_at: common_utils::date_time::now(),
@@ -154,6 +236,7 @@ impl BusinessProfileUpdateInternal {
payment_link_config,
session_expiry,
authentication_connector_details,
+ is_extended_card_info_enabled,
..source
}
}
diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rs
index effe2219a69..609a5c55f24 100644
--- a/crates/diesel_models/src/query/business_profile.rs
+++ b/crates/diesel_models/src/query/business_profile.rs
@@ -2,7 +2,9 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, T
use super::generics;
use crate::{
- business_profile::{BusinessProfile, BusinessProfileNew, BusinessProfileUpdateInternal},
+ business_profile::{
+ BusinessProfile, BusinessProfileNew, BusinessProfileUpdate, BusinessProfileUpdateInternal,
+ },
errors,
schema::business_profile::dsl,
PgPooledConn, StorageResult,
@@ -18,12 +20,12 @@ impl BusinessProfile {
pub async fn update_by_profile_id(
self,
conn: &PgPooledConn,
- business_profile: BusinessProfileUpdateInternal,
+ business_profile: BusinessProfileUpdate,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
self.profile_id.clone(),
- business_profile,
+ BusinessProfileUpdateInternal::from(business_profile),
)
.await
{
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index bbe8a8060fc..44429cc4cad 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -193,6 +193,7 @@ diesel::table! {
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
+ is_extended_card_info_enabled -> Nullable<Bool>,
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index dcb5dc14fee..3c6ab1f31d6 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1648,7 +1648,7 @@ pub async fn update_business_profile(
})
.transpose()?;
- let business_profile_update = storage::business_profile::BusinessProfileUpdateInternal {
+ let business_profile_update = storage::business_profile::BusinessProfileUpdate::Update {
profile_name: request.profile_name,
modified_at: Some(date_time::now()),
return_url: request.return_url.map(|return_url| return_url.to_string()),
@@ -1691,6 +1691,39 @@ pub async fn update_business_profile(
))
}
+pub async fn extended_card_info_toggle(
+ state: AppState,
+ profile_id: &str,
+ ext_card_info_choice: admin_types::ExtendedCardInfoChoice,
+) -> RouterResponse<admin_types::ExtendedCardInfoChoice> {
+ let db = state.store.as_ref();
+ let business_profile = db
+ .find_business_profile_by_profile_id(profile_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_string(),
+ })?;
+
+ if business_profile.is_extended_card_info_enabled.is_none()
+ || business_profile
+ .is_extended_card_info_enabled
+ .is_some_and(|existing_config| existing_config != ext_card_info_choice.enabled)
+ {
+ let business_profile_update =
+ storage::business_profile::BusinessProfileUpdate::ExtendedCardInfoUpdate {
+ is_extended_card_info_enabled: Some(ext_card_info_choice.enabled),
+ };
+
+ db.update_business_profile_by_profile_id(business_profile, business_profile_update)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_owned(),
+ })?;
+ }
+
+ Ok(service_api::ApplicationResponse::Json(ext_card_info_choice))
+}
+
pub(crate) fn validate_auth_and_metadata_type(
connector_name: api_models::enums::Connector,
val: &types::ConnectorAuthType,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index a725cc714e2..62925dcc2a5 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -5,7 +5,7 @@
use api_models::routing as routing_types;
use common_utils::ext_traits::Encode;
use diesel_models::{
- business_profile::{BusinessProfile, BusinessProfileUpdateInternal},
+ business_profile::{BusinessProfile, BusinessProfileUpdate},
configs,
};
use error_stack::ResultExt;
@@ -245,7 +245,7 @@ pub async fn update_business_profile_active_algorithm_ref(
storage::enums::TransactionType::Payout => (None, Some(ref_val)),
};
- let business_profile_update = BusinessProfileUpdateInternal {
+ let business_profile_update = BusinessProfileUpdate::Update {
profile_name: None,
return_url: None,
enable_payment_response_hash: None,
diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs
index 4d5a94b370a..7b5ade8c965 100644
--- a/crates/router/src/db/business_profile.rs
+++ b/crates/router/src/db/business_profile.rs
@@ -30,7 +30,7 @@ pub trait BusinessProfileInterface {
async fn update_business_profile_by_profile_id(
&self,
current_state: business_profile::BusinessProfile,
- business_profile_update: business_profile::BusinessProfileUpdateInternal,
+ business_profile_update: business_profile::BusinessProfileUpdate,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError>;
async fn delete_business_profile_by_profile_id_merchant_id(
@@ -90,7 +90,7 @@ impl BusinessProfileInterface for Store {
async fn update_business_profile_by_profile_id(
&self,
current_state: business_profile::BusinessProfile,
- business_profile_update: business_profile::BusinessProfileUpdateInternal,
+ business_profile_update: business_profile::BusinessProfileUpdate,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::business_profile::BusinessProfile::update_by_profile_id(
@@ -169,7 +169,7 @@ impl BusinessProfileInterface for MockDb {
async fn update_business_profile_by_profile_id(
&self,
current_state: business_profile::BusinessProfile,
- business_profile_update: business_profile::BusinessProfileUpdateInternal,
+ business_profile_update: business_profile::BusinessProfileUpdate,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
self.business_profiles
.lock()
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 9787e366e79..cc9c98be833 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2039,7 +2039,7 @@ impl BusinessProfileInterface for KafkaStore {
async fn update_business_profile_by_profile_id(
&self,
current_state: business_profile::BusinessProfile,
- business_profile_update: business_profile::BusinessProfileUpdateInternal,
+ business_profile_update: business_profile::BusinessProfileUpdate,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
self.diesel_store
.update_business_profile_by_profile_id(current_state, business_profile_update)
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index bc534dde390..63d9f840a00 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -612,3 +612,25 @@ pub async fn merchant_account_kv_status(
)
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::ToggleExtendedCardInfo))]
+pub async fn toggle_extended_card_info(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<(String, String)>,
+ json_payload: web::Json<api_models::admin::ExtendedCardInfoChoice>,
+) -> HttpResponse {
+ let flow = Flow::ToggleExtendedCardInfo;
+ let (_, profile_id) = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, _, req, _| extended_card_info_toggle(state, &profile_id, req),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ff660dbf7b7..a7c6f1486d3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1104,10 +1104,17 @@ impl BusinessProfile {
.route(web::get().to(business_profiles_list)),
)
.service(
- web::resource("/{profile_id}")
- .route(web::get().to(business_profile_retrieve))
- .route(web::post().to(business_profile_update))
- .route(web::delete().to(business_profile_delete)),
+ web::scope("/{profile_id}")
+ .service(
+ web::resource("")
+ .route(web::get().to(business_profile_retrieve))
+ .route(web::post().to(business_profile_update))
+ .route(web::delete().to(business_profile_delete)),
+ )
+ .service(
+ web::resource("/toggle_extended_card_info")
+ .route(web::post().to(toggle_extended_card_info)),
+ ),
)
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index aec3a5f2c1f..c7b1b28f2eb 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -166,7 +166,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::BusinessProfileUpdate
| Flow::BusinessProfileRetrieve
| Flow::BusinessProfileDelete
- | Flow::BusinessProfileList => Self::Business,
+ | Flow::BusinessProfileList
+ | Flow::ToggleExtendedCardInfo => Self::Business,
Flow::PaymentLinkRetrieve
| Flow::PaymentLinkInitiate
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 2cc0e21d64f..06935a29fb3 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -175,6 +175,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "authentication_connector_details",
})?,
+ is_extended_card_info_enabled: None,
})
}
}
diff --git a/crates/router/src/types/storage/business_profile.rs b/crates/router/src/types/storage/business_profile.rs
index 2ab7597bcda..d7c7d66b99e 100644
--- a/crates/router/src/types/storage/business_profile.rs
+++ b/crates/router/src/types/storage/business_profile.rs
@@ -1,3 +1,3 @@
pub use diesel_models::business_profile::{
- BusinessProfile, BusinessProfileNew, BusinessProfileUpdateInternal,
+ BusinessProfile, BusinessProfileNew, BusinessProfileUpdate, BusinessProfileUpdateInternal,
};
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 0ec6894debe..705596abe84 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -406,6 +406,8 @@ pub enum Flow {
WebhookEventDeliveryRetry,
/// Retrieve status of the Poll
RetrievePollStatus,
+ /// Toggles the extended card info feature in profile level
+ ToggleExtendedCardInfo,
}
///
diff --git a/migrations/2024-04-23-132120_add-extended-card-info-to-business-profile/down.sql b/migrations/2024-04-23-132120_add-extended-card-info-to-business-profile/down.sql
new file mode 100644
index 00000000000..e503c2dfbea
--- /dev/null
+++ b/migrations/2024-04-23-132120_add-extended-card-info-to-business-profile/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE business_profile DROP COLUMN IF EXISTS is_extended_card_info_enabled;
\ No newline at end of file
diff --git a/migrations/2024-04-23-132120_add-extended-card-info-to-business-profile/up.sql b/migrations/2024-04-23-132120_add-extended-card-info-to-business-profile/up.sql
new file mode 100644
index 00000000000..cd5e8851adf
--- /dev/null
+++ b/migrations/2024-04-23-132120_add-extended-card-info-to-business-profile/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_extended_card_info_enabled BOOLEAN DEFAULT FALSE;
\ No newline at end of file
|
2024-04-23T18:11:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds an api under `business_profile` domain, to toggle the `extended_card_info` feature with `admin_api_key` as auth.
This PR also includes refactoring of `business_profile` updation approach.
### 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)?
-->
1. Create a business profile for a merchant (Default one which gets created during merchant account creation works too)
2. Toggle extended card info feature
```
curl --location 'http://localhost:8080/account/:merchant_id/business_profile/:profile_id/toggle_extended_card_info' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"enabled": true
}'
```

3. For verifying, u could check the db if the feature is toggled using below query
```
SELECT is_extended_card_info_enabled FROM business_profile WHERE profile_id = 'profile_id';
```
## Checklist
<!-- Put an `x` in 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
|
776c1a7a24b494bf767c5524d1b8ac90472d32e2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4408
|
Bug: update refunds filters and list
Include filter for amount and merchant connector id in refunds list.
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index bf4eeb79fef..25de8821263 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -523,7 +523,7 @@ pub struct MerchantConnectorWebhookDetails {
pub additional_secret: Option<Secret<String>>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct MerchantConnectorInfo {
pub connector_label: String,
pub merchant_connector_id: String,
diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs
index 424a3191db6..7ab10a23b71 100644
--- a/crates/api_models/src/events/refund.rs
+++ b/crates/api_models/src/events/refund.rs
@@ -1,8 +1,8 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::refunds::{
- RefundListMetaData, RefundListRequest, RefundListResponse, RefundRequest, RefundResponse,
- RefundUpdateRequest, RefundsRetrieveRequest,
+ RefundListFilters, RefundListMetaData, RefundListRequest, RefundListResponse, RefundRequest,
+ RefundResponse, RefundUpdateRequest, RefundsRetrieveRequest,
};
impl ApiEventMetric for RefundRequest {
@@ -61,3 +61,9 @@ impl ApiEventMetric for RefundListMetaData {
Some(ApiEventsType::ResourceListAPI)
}
}
+
+impl ApiEventMetric for RefundListFilters {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index f1ce53580aa..6009372489d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3576,9 +3576,11 @@ pub struct PaymentListFiltersV2 {
pub authentication_type: Vec<enums::AuthenticationType>,
}
-#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct AmountFilter {
+ /// The start amount to filter list of transactions which are greater than or equal to the start amount
pub start_amount: Option<i64>,
+ /// The end amount to filter list of transactions which are less than or equal to the end amount
pub end_amount: Option<i64>,
}
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index ea28ed56af3..369aa0a6602 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -1,10 +1,15 @@
+use std::collections::HashMap;
+
use common_utils::pii;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
-use super::payments::TimeRange;
-use crate::{admin, enums};
+use super::payments::{AmountFilter, TimeRange};
+use crate::{
+ admin::{self, MerchantConnectorInfo},
+ enums,
+};
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
@@ -146,11 +151,15 @@ pub struct RefundListRequest {
pub limit: Option<i64>,
/// The starting point within a list of objects
pub offset: Option<i64>,
- /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
+ /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc)
#[serde(flatten)]
pub time_range: Option<TimeRange>,
+ /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range)
+ pub amount_filter: Option<AmountFilter>,
/// The list of connectors to filter refunds list
pub connector: Option<Vec<String>>,
+ /// The list of merchant connector ids to filter the refunds list for selected label
+ pub merchant_connector_id: Option<Vec<String>>,
/// The list of currencies to filter refunds list
#[schema(value_type = Option<Vec<Currency>>)]
pub currency: Option<Vec<enums::Currency>>,
@@ -181,6 +190,18 @@ pub struct RefundListMetaData {
pub refund_status: Vec<enums::RefundStatus>,
}
+#[derive(Clone, Debug, serde::Serialize, ToSchema)]
+pub struct RefundListFilters {
+ /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances
+ pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
+ /// The list of available currency filters
+ #[schema(value_type = Vec<Currency>)]
+ pub currency: Vec<enums::Currency>,
+ /// The list of available refund status filters
+ #[schema(value_type = Vec<RefundStatus>)]
+ pub refund_status: Vec<enums::RefundStatus>,
+}
+
/// The status for refunds
#[derive(
Debug,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 1304d350e3e..8b0974cc4f8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1514,6 +1514,7 @@ pub enum PaymentType {
PartialEq,
strum::Display,
strum::EnumString,
+ strum::EnumIter,
serde::Serialize,
serde::Deserialize,
)]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 7abbc3b77e4..6c1a32fc22d 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -418,6 +418,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::payments::TimeRange,
+ api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 2d6cac3f6e0..2ddc5e1f6c2 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1,9 +1,16 @@
pub mod validator;
+#[cfg(feature = "olap")]
+use std::collections::HashMap;
+
+#[cfg(feature = "olap")]
+use api_models::admin::MerchantConnectorInfo;
use common_utils::ext_traits::AsyncExt;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use scheduler::{consumer::types::process_data, utils as process_tracker_utils};
+#[cfg(feature = "olap")]
+use strum::IntoEnumIterator;
use crate::{
consts,
@@ -767,6 +774,48 @@ pub async fn refund_filter_list(
Ok(services::ApplicationResponse::Json(filter_list))
}
+#[instrument(skip_all)]
+#[cfg(feature = "olap")]
+pub async fn get_filters_for_refunds(
+ state: AppState,
+ merchant_account: domain::MerchantAccount,
+) -> RouterResponse<api_models::refunds::RefundListFilters> {
+ let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
+ super::admin::list_payment_connectors(state, merchant_account.merchant_id).await?
+ {
+ data
+ } else {
+ return Err(errors::ApiErrorResponse::InternalServerError.into());
+ };
+
+ let connector_map = merchant_connector_accounts
+ .into_iter()
+ .filter_map(|merchant_connector_account| {
+ merchant_connector_account.connector_label.map(|label| {
+ let info = MerchantConnectorInfo {
+ connector_label: label,
+ merchant_connector_id: merchant_connector_account.merchant_connector_id,
+ };
+ (merchant_connector_account.connector_name, info)
+ })
+ })
+ .fold(
+ HashMap::new(),
+ |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| {
+ map.entry(connector_name).or_default().push(info);
+ map
+ },
+ );
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::refunds::RefundListFilters {
+ connector: connector_map,
+ currency: enums::Currency::iter().collect(),
+ refund_status: enums::RefundStatus::iter().collect(),
+ },
+ ))
+}
+
impl ForeignFrom<storage::Refund> for api::RefundResponse {
fn foreign_from(refund: storage::Refund) -> Self {
let refund = refund;
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index ca3921d6199..df1130b7af6 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -930,6 +930,7 @@ impl RefundInterface for MockDb {
offset: i64,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let mut unique_connectors = HashSet::new();
+ let mut unique_merchant_connector_ids = HashSet::new();
let mut unique_currencies = HashSet::new();
let mut unique_statuses = HashSet::new();
@@ -940,6 +941,14 @@ impl RefundInterface for MockDb {
});
}
+ if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id {
+ merchant_connector_ids
+ .iter()
+ .for_each(|unique_merchant_connector_id| {
+ unique_merchant_connector_ids.insert(unique_merchant_connector_id);
+ });
+ }
+
if let Some(currencies) = &refund_details.currency {
currencies.iter().for_each(|currency| {
unique_currencies.insert(currency);
@@ -982,9 +991,25 @@ impl RefundInterface for MockDb {
range.end_time.unwrap_or_else(common_utils::date_time::now)
})
})
+ .filter(|refund| {
+ refund_details
+ .amount_filter
+ .as_ref()
+ .map_or(true, |amount| {
+ refund.refund_amount >= amount.start_amount.unwrap_or(i64::MIN)
+ && refund.refund_amount <= amount.end_amount.unwrap_or(i64::MAX)
+ })
+ })
.filter(|refund| {
unique_connectors.is_empty() || unique_connectors.contains(&refund.connector)
})
+ .filter(|refund| {
+ unique_merchant_connector_ids.is_empty()
+ || refund
+ .merchant_connector_id
+ .as_ref()
+ .map_or(false, |id| unique_merchant_connector_ids.contains(id))
+ })
.filter(|refund| {
unique_currencies.is_empty() || unique_currencies.contains(&refund.currency)
})
@@ -1054,6 +1079,7 @@ impl RefundInterface for MockDb {
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let mut unique_connectors = HashSet::new();
+ let mut unique_merchant_connector_ids = HashSet::new();
let mut unique_currencies = HashSet::new();
let mut unique_statuses = HashSet::new();
@@ -1064,6 +1090,14 @@ impl RefundInterface for MockDb {
});
}
+ if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id {
+ merchant_connector_ids
+ .iter()
+ .for_each(|unique_merchant_connector_id| {
+ unique_merchant_connector_ids.insert(unique_merchant_connector_id);
+ });
+ }
+
if let Some(currencies) = &refund_details.currency {
currencies.iter().for_each(|currency| {
unique_currencies.insert(currency);
@@ -1106,9 +1140,25 @@ impl RefundInterface for MockDb {
range.end_time.unwrap_or_else(common_utils::date_time::now)
})
})
+ .filter(|refund| {
+ refund_details
+ .amount_filter
+ .as_ref()
+ .map_or(true, |amount| {
+ refund.refund_amount >= amount.start_amount.unwrap_or(i64::MIN)
+ && refund.refund_amount <= amount.end_amount.unwrap_or(i64::MAX)
+ })
+ })
.filter(|refund| {
unique_connectors.is_empty() || unique_connectors.contains(&refund.connector)
})
+ .filter(|refund| {
+ unique_merchant_connector_ids.is_empty()
+ || refund
+ .merchant_connector_id
+ .as_ref()
+ .map_or(false, |id| unique_merchant_connector_ids.contains(id))
+ })
.filter(|refund| {
unique_currencies.is_empty() || unique_currencies.contains(&refund.currency)
})
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 1c680b8bc8e..21cc994381e 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -333,7 +333,7 @@ impl Payments {
.route(web::post().to(payments_list_by_filter)),
)
.service(web::resource("/filter").route(web::post().to(get_filters_for_payments)))
- .service(web::resource("/filter_v2").route(web::get().to(get_payment_filters)))
+ .service(web::resource("/v2/filter").route(web::get().to(get_payment_filters)))
}
#[cfg(feature = "oltp")]
{
@@ -716,7 +716,8 @@ impl Refunds {
{
route = route
.service(web::resource("/list").route(web::post().to(refunds_list)))
- .service(web::resource("/filter").route(web::post().to(refunds_filter_list)));
+ .service(web::resource("/filter").route(web::post().to(refunds_filter_list)))
+ .service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters)));
}
#[cfg(feature = "oltp")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 7b10247dded..30b582079e3 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -136,7 +136,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::RefundsRetrieve
| Flow::RefundsRetrieveForceSync
| Flow::RefundsUpdate
- | Flow::RefundsList => Self::Refunds,
+ | Flow::RefundsList
+ | Flow::RefundsFilters => Self::Refunds,
Flow::FrmFulfillment
| Flow::IncomingWebhookReceive
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index d68c7138213..3df6c871668 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -230,6 +230,7 @@ pub async fn refunds_list(
)
.await
}
+
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
@@ -267,3 +268,36 @@ pub async fn refunds_filter_list(
)
.await
}
+
+/// Refunds - Filter V2
+///
+/// To list the refunds filters associated with list of connectors, currencies and payment statuses
+#[utoipa::path(
+ get,
+ path = "/refunds/v2/filter",
+ responses(
+ (status = 200, description = "List of static filters", body = RefundListFilters),
+ ),
+ tag = "Refunds",
+ operation_id = "List all filters for Refunds",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
+#[cfg(feature = "olap")]
+pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::RefundsFilters;
+ api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth, _, _| get_filters_for_refunds(state, auth.merchant_account),
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::RefundRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ )
+ .await
+}
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 76bdf8655f6..75030721ec5 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -1,3 +1,4 @@
+use api_models::payments::AmountFilter;
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::errors::CustomResult;
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
@@ -104,10 +105,30 @@ impl RefundDbExt for Refund {
}
}
- if let Some(connector) = refund_list_details.clone().connector {
+ filter = match refund_list_details.amount_filter {
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: Some(end),
+ }) => filter.filter(dsl::refund_amount.between(start, end)),
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: None,
+ }) => filter.filter(dsl::refund_amount.ge(start)),
+ Some(AmountFilter {
+ start_amount: None,
+ end_amount: Some(end),
+ }) => filter.filter(dsl::refund_amount.le(end)),
+ _ => filter,
+ };
+
+ if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
+ if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
+ filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id));
+ }
+
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
@@ -227,10 +248,30 @@ impl RefundDbExt for Refund {
}
}
- if let Some(connector) = refund_list_details.clone().connector {
+ filter = match refund_list_details.amount_filter {
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: Some(end),
+ }) => filter.filter(dsl::refund_amount.between(start, end)),
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: None,
+ }) => filter.filter(dsl::refund_amount.ge(start)),
+ Some(AmountFilter {
+ start_amount: None,
+ end_amount: Some(end),
+ }) => filter.filter(dsl::refund_amount.le(end)),
+ _ => filter,
+ };
+
+ if let Some(connector) = refund_list_details.connector.clone() {
filter = filter.filter(dsl::connector.eq_any(connector));
}
+ if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {
+ filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
+ }
+
if let Some(filter_currency) = &refund_list_details.currency {
filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index a893386ab87..ffa492bc60d 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -190,6 +190,8 @@ pub enum Flow {
RefundsUpdate,
/// Refunds list flow.
RefundsList,
+ /// Refunds filters flow
+ RefundsFilters,
// Retrieve forex flow.
RetrieveForexFlow,
/// Toggles recon service for a merchant.
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 259d1669523..cb82a2e7675 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4910,6 +4910,23 @@
"AliPayRedirection": {
"type": "object"
},
+ "AmountFilter": {
+ "type": "object",
+ "properties": {
+ "start_amount": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The start amount to filter list of transactions which are greater than or equal to the start amount",
+ "nullable": true
+ },
+ "end_amount": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The end amount to filter list of transactions which are less than or equal to the end amount",
+ "nullable": true
+ }
+ }
+ },
"AmountInfo": {
"type": "object",
"required": [
@@ -16785,6 +16802,14 @@
"description": "The starting point within a list of objects",
"nullable": true
},
+ "amount_filter": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AmountFilter"
+ }
+ ],
+ "nullable": true
+ },
"connector": {
"type": "array",
"items": {
@@ -16793,6 +16818,14 @@
"description": "The list of connectors to filter refunds list",
"nullable": true
},
+ "merchant_connector_id": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "The list of merchant connector ids to filter the refunds list for selected label",
+ "nullable": true
+ },
"currency": {
"type": "array",
"items": {
|
2024-04-22T07:31:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The PR:
- Adds support for new `filter_v2` api to get list of available filters for refunds quickly: connector with their corresponding label with merchant_connector_ids, currency and refund status. This api is quicker than previous one and gives static and dynamic filter. In this list of available value doesn't depend on refunds that are made (present in table). But these are static and configuration dependent.
- Modifies existing refunds list as per filters applied (also manages pagination result etc), we can filter list by amount and merchant connector ids as well and the application of previous filters on list remains same.
- _Also changed payments filter v2 (it is not being used as of now)_ .
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes #4408
## How did you test it?
To get list of filters:
```
curl --location 'http://localhost:8080/refunds/filter_v2' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response:
```
{
"connector": {
"paypal_test": [
{
"connector_label": "payal_test_default",
"merchant_connector_id": "mca_test"
}
},
"currency": [
"AED",
"ALL",
"AMD",
"ANG",
"AOA",
"ARS",
"AUD",
"AWG",
"AZN",
"BAM",
"BBD",
"BDT",
"BGN",
"BHD",
"BIF",
"BMD",
"BND",
"BOB",
"BRL",
"BSD",
"BWP",
"BYN",
"BZD",
"CAD",
"CHF",
"CLP",
"CNY",
"COP",
"CRC",
"CUP",
"CVE",
"CZK",
"DJF",
"DKK",
"DOP",
"DZD",
"EGP",
"ETB",
"EUR",
"FJD",
"FKP",
"GBP",
"GEL",
"GHS",
"GIP",
"GMD",
"GNF",
"GTQ",
"GYD",
"HKD",
"HNL",
"HRK",
"HTG",
"HUF",
"IDR",
"ILS",
"INR",
"IQD",
"JMD",
"JOD",
"JPY",
"KES",
"KGS",
"KHR",
"KMF",
"KRW",
"KWD",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"LYD",
"MAD",
"MDL",
"MGA",
"MKD",
"MMK",
"MNT",
"MOP",
"MRU",
"MUR",
"MVR",
"MWK",
"MXN",
"MYR",
"MZN",
"NAD",
"NGN",
"NIO",
"NOK",
"NPR",
"NZD",
"OMR",
"PAB",
"PEN",
"PGK",
"PHP",
"PKR",
"PLN",
"PYG",
"QAR",
"RON",
"RSD",
"RUB",
"RWF",
"SAR",
"SBD",
"SCR",
"SEK",
"SGD",
"SHP",
"SLE",
"SLL",
"SOS",
"SRD",
"SSP",
"STN",
"SVC",
"SZL",
"THB",
"TND",
"TOP",
"TRY",
"TTD",
"TWD",
"TZS",
"UAH",
"UGX",
"USD",
"UYU",
"UZS",
"VES",
"VND",
"VUV",
"WST",
"XAF",
"XCD",
"XOF",
"XPF",
"YER",
"ZAR",
"ZMW"
],
"refund_status": [
"Failure",
"ManualReview",
"Pending",
"Success",
"TransactionFailure"
]
}
```
To filter refunds list by new parameters i.e., amount and merchant_connector_id
```
curl --location 'http://localhost:8080/refunds/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_connector_id": ["mca_test1", "mca_test_2"],
"connector": ["paypal_test"],
"amount_filter": {
"start_amount": 12600,
"end_amount": 12600
}
}'
```
Response:
```
{
"count": 1,
"total_count": 1,
"data": [
{
"refund_id": "test_YqXmZZAtH9Hr97ZVA2lo",
"payment_id": "test_KuyhzmNelel8VKEVLHUi",
"amount": 12600,
"currency": "USD",
"status": "succeeded",
"reason": "Sample Refund",
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-04-22T05:58:24.000Z",
"updated_at": "2024-04-22T05:58:24.000Z",
"connector": "paypal_test",
"profile_id": "pro_itP1UHdaBjqXsFF0WoAm",
"merchant_connector_id": "mca_test1"
}
]
}
```
## Checklist
<!-- Put an `x` in 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
|
2a302eb5973c64d8b77f8110fdbeb536ccbe1488
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4397
|
Bug: [FEATURE] Implementing iDEAL and Giropay payment methods with Multisafe
### Feature Description
Add iDEAL and Giropay payment processors in [Multisafepay](https://docs.hyperswitch.io/hyperswitch-cloud/connectors/available-connectors/multisafepay) connector.
Whole description can be found in #4143 discussion.
### Possible Implementation
## Proposal: **Implementing iDEAL and Giropay payment methods with Multisafe** #4143
### Objective
Add iDEAL and Giropay payment processors in [Multisafepay](https://docs.hyperswitch.io/hyperswitch-cloud/connectors/available-connectors/multisafepay) connector.
### Background
Currently multisafepay provides various payment processors from Banking Methods, BNPL, Credit and Debit cards, Prepaid cards and Wallets segment. From these hyperswitch's multisafepay connector provides support for credit cards and debit cards, mendate payements, GooglePay, Paypal and Klarna only. iDEAL and Giropay are from "Banking Methods" category.
#### iDeal
iDeal has direct and re-directed flow which is showed below:

**direct**: given **iDEAL issuer code** user customer will be directly redirected to the bank’s
page
**redirect:** Redirect customer to payment’s page to select their bank.
#### Giropay
giropay has only redirect flow which is exactly same flow as iDEAL’s redirect flow.

### Approach
For iDeal deciding direct or re-direct payment type:
If bank name is provided in `PaymentMethodData` then direct path should be used otherwise redirect. If direct flow is selected then in `MultisafepayPaymentsRequest` ’s `gateway_info` must have **`issuer_id`** field.
List of iDEAL issuers and respective code is given below ([source](https://docs.multisafepay.com/reference/listidealissuers))
| Code | Description |
| ---- | --------------------- |
| 0031 | ABN AMRO |
| 0761 | ASN Bank |
| 4371 | bunq |
| 1235 | Handelsbanken |
| 9927 | Nationale Nederlanden |
| 9926 | N26 |
| 0721 | ING |
| 0801 | Knab |
| 0021 | Rabobank |
| 0771 | Regio Bank |
| 1099 | Revolut |
| 0751 | SNS Bank |
| 0511 | Triodos Bank |
| 0161 | Van Lanschot Bankiers |
| 0806 | Yoursafe |
Only these banks should be allowed in `PaymentMethodData` for iDEAL.
#### Implementation
All the changes will be in `connector/multisafepay.rs` file and in the enums and traits for request object
- Add `Ideal` and `Giropay` in `Gateway` enum
- changes in `impl TryFrom<&CheckoutRouterData<&T>> for MultisafepayPaymentsRequest`
- for `payment_type` : add pattern for redirect “giropay” and “iDeal” and direct “iDeal” payments
- for `gateway` : add `BankRedirectData::Ideal` and `BankRedirectData::Geropay` pattern
- for `gateway_info`: Only for direct “iDeal” payments,
- `issuer_id` : get issuer id from the table above
There are also optional `gateway_info` fields for modifying payment behaviours like **`allow_change_amount` , `min_amount` and `max_amount`** which are related to QR code payment in direct flop.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index a42a6a8c323..738edcbda84 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -4,11 +4,12 @@ eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban
eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau"
ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe"
ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
+ideal.multisafepay.banks = "abn_amro, asn_bank, bunq, handelsbanken, nationale_nederlanden, n26, ing, knab, rabobank, regiobank, revolut, sns_bank,triodos_bank, van_lanschot, yoursafe"
online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"
online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24"
online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo"
-online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank"
+online_banking_thailand.adyen.banks = "bangkok_bank,krungsrgiri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank"
open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"
przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank"
@@ -137,10 +138,9 @@ pay_later.klarna.connector_list = "adyen" # Mandate suppor
wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica" # Mandate supported payment method type and connector for wallets
wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica" # Mandate supported payment method type and connector for wallets
wallet.paypal.connector_list = "adyen" # Mandate supported payment method type and connector for wallets
-bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
+bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect
bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
-bank_redirect.giropay.connector_list = "adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
-
+bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 0cc74067337..b4e02172dfc 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -4,6 +4,7 @@ eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban
eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau"
ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe"
ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
+ideal.multisafepay.banks = "abn_amro, asn_bank, bunq, handelsbanken, nationale_nederlanden, n26, ing, knab, rabobank, regiobank, revolut, sns_bank,triodos_bank, van_lanschot, yoursafe"
online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"
online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24"
@@ -137,9 +138,9 @@ pay_later.klarna.connector_list = "adyen" # Mandate suppor
wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica" # Mandate supported payment method type and connector for wallets
wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica" # Mandate supported payment method type and connector for wallets
wallet.paypal.connector_list = "adyen" # Mandate supported payment method type and connector for wallets
-bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
+bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect
bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
-bank_redirect.giropay.connector_list = "adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
+bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index a61ad70eccf..180cf56db4d 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -4,6 +4,7 @@ eps.adyen.banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban
eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau"
ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe"
ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
+ideal.multisafepay.banks = "abn_amro, asn_bank, bunq, handelsbanken, nationale_nederlanden, n26, ing, knab, rabobank, regiobank, revolut, sns_bank,triodos_bank, van_lanschot, yoursafe"
online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"
online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24"
@@ -137,9 +138,9 @@ pay_later.klarna.connector_list = "adyen" # Mandate suppor
wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica" # Mandate supported payment method type and connector for wallets
wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica" # Mandate supported payment method type and connector for wallets
wallet.paypal.connector_list = "adyen" # Mandate supported payment method type and connector for wallets
-bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
+bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect
bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
-bank_redirect.giropay.connector_list = "adyen,globalpay" # Mandate supported payment method type and connector for bank_redirect
+bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
diff --git a/config/development.toml b/config/development.toml
index 95cadf56617..a742edcf727 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -281,6 +281,7 @@ adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban
[bank_config.ideal]
stripe = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" }
adyen = { banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot, yoursafe" }
+multisafepay = { banks="abn_amro, asn_bank, bunq, handelsbanken, nationale_nederlanden, n26, ing, knab, rabobank, regiobank, revolut, sns_bank,triodos_bank, van_lanschot, yoursafe" }
[bank_config.online_banking_czech_republic]
adyen = { banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" }
@@ -533,9 +534,9 @@ card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,global
bank_debit.ach = { connector_list = "gocardless" }
bank_debit.becs = { connector_list = "gocardless" }
bank_debit.sepa = { connector_list = "gocardless" }
-bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" }
+bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay,multisafepay" }
bank_redirect.sofort = { connector_list = "stripe,adyen,globalpay" }
-bank_redirect.giropay = { connector_list = "adyen,globalpay" }
+bank_redirect.giropay = { connector_list = "adyen,globalpay,multisafepay" }
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" }
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index d3aadcd0607..49e4c516265 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -1,3 +1,4 @@
+use api_models::enums::BankNames;
use common_enums::AttemptStatus;
use common_utils::pii::{Email, IpAddress};
use masking::ExposeInterface;
@@ -52,6 +53,8 @@ pub enum Gateway {
Klarna,
Googlepay,
Paypal,
+ Ideal,
+ Giropay,
}
#[serde_with::skip_serializing_none]
@@ -162,6 +165,7 @@ pub enum GatewayInfo {
Card(CardInfo),
Wallet(WalletInfo),
PayLater(PayLaterInfo),
+ BankRedirect(BankRedirectInfo),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
@@ -170,6 +174,207 @@ pub enum WalletInfo {
GooglePay(GpayInfo),
}
+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
+#[serde(untagged)]
+pub enum BankRedirectInfo {
+ Ideal(IdealInfo),
+}
+
+#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
+pub struct IdealInfo {
+ pub issuer_id: MultisafepayBankNames,
+}
+
+#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
+pub enum MultisafepayBankNames {
+ #[serde(rename = "0031")]
+ AbnAmro,
+ #[serde(rename = "0761")]
+ AsnBank,
+ #[serde(rename = "4371")]
+ Bunq,
+ #[serde(rename = "0721")]
+ Ing,
+ #[serde(rename = "0801")]
+ Knab,
+ #[serde(rename = "9926")]
+ N26,
+ #[serde(rename = "9927")]
+ NationaleNederlanden,
+ #[serde(rename = "0021")]
+ Rabobank,
+ #[serde(rename = "0771")]
+ Regiobank,
+ #[serde(rename = "1099")]
+ Revolut,
+ #[serde(rename = "0751")]
+ SnsBank,
+ #[serde(rename = "0511")]
+ TriodosBank,
+ #[serde(rename = "0161")]
+ VanLanschot,
+ #[serde(rename = "0806")]
+ Yoursafe,
+ #[serde(rename = "1235")]
+ Handelsbanken,
+}
+
+impl TryFrom<&BankNames> for MultisafepayBankNames {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
+ match bank {
+ BankNames::AbnAmro => Ok(Self::AbnAmro),
+ BankNames::AsnBank => Ok(Self::AsnBank),
+ BankNames::Bunq => Ok(Self::Bunq),
+ BankNames::Ing => Ok(Self::Ing),
+ BankNames::Knab => Ok(Self::Knab),
+ BankNames::N26 => Ok(Self::N26),
+ BankNames::NationaleNederlanden => Ok(Self::NationaleNederlanden),
+ BankNames::Rabobank => Ok(Self::Rabobank),
+ BankNames::Regiobank => Ok(Self::Regiobank),
+ BankNames::Revolut => Ok(Self::Revolut),
+ BankNames::SnsBank => Ok(Self::SnsBank),
+ BankNames::TriodosBank => Ok(Self::TriodosBank),
+ BankNames::VanLanschot => Ok(Self::VanLanschot),
+ BankNames::Yoursafe => Ok(Self::Yoursafe),
+ BankNames::Handelsbanken => Ok(Self::Handelsbanken),
+ BankNames::AmericanExpress
+ | BankNames::AffinBank
+ | BankNames::AgroBank
+ | BankNames::AllianceBank
+ | BankNames::AmBank
+ | BankNames::BankOfAmerica
+ | BankNames::BankIslam
+ | BankNames::BankMuamalat
+ | BankNames::BankRakyat
+ | BankNames::BankSimpananNasional
+ | BankNames::Barclays
+ | BankNames::BlikPSP
+ | BankNames::CapitalOne
+ | BankNames::Chase
+ | BankNames::Citi
+ | BankNames::CimbBank
+ | BankNames::Discover
+ | BankNames::NavyFederalCreditUnion
+ | BankNames::PentagonFederalCreditUnion
+ | BankNames::SynchronyBank
+ | BankNames::WellsFargo
+ | BankNames::HongLeongBank
+ | BankNames::HsbcBank
+ | BankNames::KuwaitFinanceHouse
+ | BankNames::Moneyou
+ | BankNames::ArzteUndApothekerBank
+ | BankNames::AustrianAnadiBankAg
+ | BankNames::BankAustria
+ | BankNames::Bank99Ag
+ | BankNames::BankhausCarlSpangler
+ | BankNames::BankhausSchelhammerUndSchatteraAg
+ | BankNames::BankMillennium
+ | BankNames::BankPEKAOSA
+ | BankNames::BawagPskAg
+ | BankNames::BksBankAg
+ | BankNames::BrullKallmusBankAg
+ | BankNames::BtvVierLanderBank
+ | BankNames::CapitalBankGraweGruppeAg
+ | BankNames::CeskaSporitelna
+ | BankNames::Dolomitenbank
+ | BankNames::EasybankAg
+ | BankNames::EPlatbyVUB
+ | BankNames::ErsteBankUndSparkassen
+ | BankNames::FrieslandBank
+ | BankNames::HypoAlpeadriabankInternationalAg
+ | BankNames::HypoNoeLbFurNiederosterreichUWien
+ | BankNames::HypoOberosterreichSalzburgSteiermark
+ | BankNames::HypoTirolBankAg
+ | BankNames::HypoVorarlbergBankAg
+ | BankNames::HypoBankBurgenlandAktiengesellschaft
+ | BankNames::KomercniBanka
+ | BankNames::MBank
+ | BankNames::MarchfelderBank
+ | BankNames::Maybank
+ | BankNames::OberbankAg
+ | BankNames::OsterreichischeArzteUndApothekerbank
+ | BankNames::OcbcBank
+ | BankNames::PayWithING
+ | BankNames::PlaceZIPKO
+ | BankNames::PlatnoscOnlineKartaPlatnicza
+ | BankNames::PosojilnicaBankEGen
+ | BankNames::PostovaBanka
+ | BankNames::PublicBank
+ | BankNames::RaiffeisenBankengruppeOsterreich
+ | BankNames::RhbBank
+ | BankNames::SchelhammerCapitalBankAg
+ | BankNames::StandardCharteredBank
+ | BankNames::SchoellerbankAg
+ | BankNames::SpardaBankWien
+ | BankNames::SporoPay
+ | BankNames::SantanderPrzelew24
+ | BankNames::TatraPay
+ | BankNames::Viamo
+ | BankNames::VolksbankGruppe
+ | BankNames::VolkskreditbankAg
+ | BankNames::VrBankBraunau
+ | BankNames::UobBank
+ | BankNames::PayWithAliorBank
+ | BankNames::BankiSpoldzielcze
+ | BankNames::PayWithInteligo
+ | BankNames::BNPParibasPoland
+ | BankNames::BankNowySA
+ | BankNames::CreditAgricole
+ | BankNames::PayWithBOS
+ | BankNames::PayWithCitiHandlowy
+ | BankNames::PayWithPlusBank
+ | BankNames::ToyotaBank
+ | BankNames::VeloBank
+ | BankNames::ETransferPocztowy24
+ | BankNames::PlusBank
+ | BankNames::EtransferPocztowy24
+ | BankNames::BankiSpbdzielcze
+ | BankNames::BankNowyBfgSa
+ | BankNames::GetinBank
+ | BankNames::Blik
+ | BankNames::NoblePay
+ | BankNames::IdeaBank
+ | BankNames::EnveloBank
+ | BankNames::NestPrzelew
+ | BankNames::MbankMtransfer
+ | BankNames::Inteligo
+ | BankNames::PbacZIpko
+ | BankNames::BnpParibas
+ | BankNames::BankPekaoSa
+ | BankNames::VolkswagenBank
+ | BankNames::AliorBank
+ | BankNames::Boz
+ | BankNames::BangkokBank
+ | BankNames::KrungsriBank
+ | BankNames::KrungThaiBank
+ | BankNames::TheSiamCommercialBank
+ | BankNames::KasikornBank
+ | BankNames::OpenBankSuccess
+ | BankNames::OpenBankFailure
+ | BankNames::OpenBankCancelled
+ | BankNames::Aib
+ | BankNames::BankOfScotland
+ | BankNames::DanskeBank
+ | BankNames::FirstDirect
+ | BankNames::FirstTrust
+ | BankNames::Halifax
+ | BankNames::Lloyds
+ | BankNames::Monzo
+ | BankNames::NatWest
+ | BankNames::NationwideBank
+ | BankNames::RoyalBankOfScotland
+ | BankNames::Starling
+ | BankNames::TsbBank
+ | BankNames::TescoBank
+ | BankNames::UlsterBank => Err(Into::into(errors::ConnectorError::NotSupported {
+ message: String::from("BankRedirect"),
+ connector: "Multisafepay",
+ })),
+ }
+ }
+}
+
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct DeliveryObject {
first_name: Secret<String>,
@@ -300,6 +505,29 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
+ domain::PaymentMethodData::BankRedirect(ref bank_data) => match bank_data {
+ domain::BankRedirectData::Giropay { .. } => Type::Redirect,
+ domain::BankRedirectData::Ideal { .. } => Type::Direct,
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Eps { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Sofort { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
+ ))?
+ }
+ },
domain::PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
_ => Type::Redirect,
};
@@ -339,13 +567,35 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
}),
+ domain::PaymentMethodData::BankRedirect(ref bank_data) => Some(match bank_data {
+ domain::BankRedirectData::Giropay { .. } => Gateway::Giropay,
+ domain::BankRedirectData::Ideal { .. } => Gateway::Ideal,
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Eps { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Sofort { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
+ ))?
+ }
+ }),
domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaRedirect {}) => {
Some(Gateway::Klarna)
}
domain::PaymentMethodData::MandatePayment => None,
domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
| domain::PaymentMethodData::BankDebit(_)
| domain::PaymentMethodData::BankTransfer(_)
| domain::PaymentMethodData::Crypto(_)
@@ -493,9 +743,37 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
}),
}))
}
+ domain::PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
+ match bank_redirect_data {
+ domain::BankRedirectData::Ideal { bank_name, .. } => Some(
+ GatewayInfo::BankRedirect(BankRedirectInfo::Ideal(IdealInfo {
+ issuer_id: MultisafepayBankNames::try_from(&bank_name.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "ideal.bank_name",
+ },
+ )?)?,
+ })),
+ ),
+ domain::BankRedirectData::BancontactCard { .. }
+ | domain::BankRedirectData::Bizum { .. }
+ | domain::BankRedirectData::Blik { .. }
+ | domain::BankRedirectData::Eps { .. }
+ | domain::BankRedirectData::Giropay { .. }
+ | domain::BankRedirectData::Interac { .. }
+ | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | domain::BankRedirectData::OnlineBankingFinland { .. }
+ | domain::BankRedirectData::OnlineBankingPoland { .. }
+ | domain::BankRedirectData::OnlineBankingSlovakia { .. }
+ | domain::BankRedirectData::OpenBankingUk { .. }
+ | domain::BankRedirectData::Przelewy24 { .. }
+ | domain::BankRedirectData::Sofort { .. }
+ | domain::BankRedirectData::Trustly { .. }
+ | domain::BankRedirectData::OnlineBankingFpx { .. }
+ | domain::BankRedirectData::OnlineBankingThailand { .. } => None,
+ }
+ }
domain::PaymentMethodData::MandatePayment => None,
domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::BankRedirect(_)
| domain::PaymentMethodData::BankDebit(_)
| domain::PaymentMethodData::BankTransfer(_)
| domain::PaymentMethodData::Crypto(_)
|
2024-04-19T08:53:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add iDEAL and Giropay payment processors in [Multisafepay](https://docs.hyperswitch.io/hyperswitch-cloud/connectors/available-connectors/multisafepay) connector.
Whole description can be found in https://github.com/juspay/hyperswitch/discussions/4143 discussion.
### 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).
-->
Solves the issue #4397
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
I have tested the Multisafe payment connector for Giropay and iDeal methods in Postman suit. You can find my fork of Postman's collection below. In `Payments - Create iDeal Payment` and `Payments - Create Giropay Direct` in `Quick Start` are the requests for the payments.
### iDeal
By requesting the iDeal payment method with "Ing" bank name, a redirection link can be found, redirecting to the test portal of Multisafepay, where we can see the bank name we selected.
<img width="1166" alt="image" src="https://github.com/juspay/hyperswitch/assets/52617262/03330626-f5cf-4dae-8101-8994bb2dd273">
<img width="842" alt="image" src="https://github.com/juspay/hyperswitch/assets/52617262/2f6afb1f-0b3f-445c-8bcd-f1971cbfe82d">
Also, passing bank names not supported by iDeal raises an Error.
<img width="1212" alt="image" src="https://github.com/juspay/hyperswitch/assets/52617262/a1a80fc1-888b-48d6-934f-916b1dfa2d45">
Not Passing the bank name in the `payment_method_data` returns an error, too.
<img width="1210" alt="image" src="https://github.com/juspay/hyperswitch/assets/52617262/82b466c4-db37-4f10-8534-716509e1640b">
### Giropay
Giropay doesn't support the direct method, so it is not compulsory to enter `bank_name` into the `payment_method_data`. After a successful request to Multisafepay, We will get a redirection link to the Mutisafepay payment's page.
<img width="1200" alt="image" src="https://github.com/juspay/hyperswitch/assets/52617262/abcaa114-7a7c-4de5-a51f-96528d7f2cab">
Mutisafepay payment page.
<img width="829" alt="image" src="https://github.com/juspay/hyperswitch/assets/52617262/faf1107b-c0a9-4148-b4fa-835b3da8ebe1">
[<img src="https://run.pstmn.io/button.svg" alt="Run In Postman" style="width: 128px; height: 32px;">](https://app.getpostman.com/run-collection/10729153-3cd01106-4ad2-4570-a1dd-a2629eb55658?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D10729153-3cd01106-4ad2-4570-a1dd-a2629eb55658%26entityType%3Dcollection%26workspaceId%3D88823756-0d03-4feb-a41e-364916fb37b0)
## Checklist
<!-- Put an `x` in 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
|
97e4f1af90134ad733e3c715a954c719e8a2c5fe
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4399
|
Bug: [Refactor] PostAuth FRM flow
This issues is regarding implementing revised PostAuth Frm. Below is the revised flow.
**PostAuth flow**
- The underlying FRM connector is invoked post authentication of the user from the bank.
- If a transaction’s capture method was set to automatic, it is updated to manual for avoiding automatic capture.
- Once the user completes the authentication, the underlying FRM connector is invoked. The decision whether or not to
proceed with the txn is based on the status / score returned.
**Possible actions based on the status**
- Continue on **Accept**
- Continue with the **transaction**
- Halt on **Decline**
- Mark the transaction as cancelled
- Approve / Decline on **Manual Review**
- Hold the txn in manual review state. Merchants can list and review such transactions.
- If approved, payment is captured
- If declined, payment is voided
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 0681edbb15a..44e17754696 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2249,7 +2249,7 @@ pub enum FrmSuggestion {
#[default]
FrmCancelTransaction,
FrmManualReview,
- FrmAutoRefund,
+ FrmAuthorizeTransaction, // When manual capture payment which was marked fraud and held, when approved needs to be authorized.
}
#[derive(
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 0c165632047..7e406ca24d5 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -303,6 +303,7 @@ pub enum PaymentAttemptUpdate {
currency: storage_enums::Currency,
status: storage_enums::AttemptStatus,
authentication_type: Option<storage_enums::AuthenticationType>,
+ capture_method: Option<storage_enums::CaptureMethod>,
payment_method: Option<storage_enums::PaymentMethod>,
browser_info: Option<serde_json::Value>,
connector: Option<String>,
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index 0ab39bcbad2..a5e631b5ac3 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -182,6 +182,7 @@ pub enum PaymentIntentUpdate {
updated_by: String,
},
ApproveUpdate {
+ status: storage_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
@@ -382,9 +383,11 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
..Default::default()
},
PaymentIntentUpdate::ApproveUpdate {
+ status,
merchant_decision,
updated_by,
} => Self {
+ status: Some(status),
merchant_decision,
updated_by,
..Default::default()
diff --git a/crates/diesel_models/src/fraud_check.rs b/crates/diesel_models/src/fraud_check.rs
index 8c20fe466af..5513afcfbd1 100644
--- a/crates/diesel_models/src/fraud_check.rs
+++ b/crates/diesel_models/src/fraud_check.rs
@@ -1,3 +1,4 @@
+use common_enums as storage_enums;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use masking::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -25,6 +26,7 @@ pub struct FraudCheck {
pub metadata: Option<serde_json::Value>,
pub modified_at: PrimitiveDateTime,
pub last_step: FraudCheckLastStep,
+ pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -46,6 +48,7 @@ pub struct FraudCheckNew {
pub metadata: Option<serde_json::Value>,
pub modified_at: PrimitiveDateTime,
pub last_step: FraudCheckLastStep,
+ pub payment_capture_method: Option<storage_enums::CaptureMethod>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -59,6 +62,7 @@ pub enum FraudCheckUpdate {
metadata: Option<serde_json::Value>,
modified_at: PrimitiveDateTime,
last_step: FraudCheckLastStep,
+ payment_capture_method: Option<storage_enums::CaptureMethod>,
},
ErrorUpdate {
status: FraudCheckStatus,
@@ -76,6 +80,7 @@ pub struct FraudCheckUpdateInternal {
frm_error: Option<Option<String>>,
metadata: Option<serde_json::Value>,
last_step: FraudCheckLastStep,
+ payment_capture_method: Option<storage_enums::CaptureMethod>,
}
impl From<FraudCheckUpdate> for FraudCheckUpdateInternal {
@@ -89,6 +94,7 @@ impl From<FraudCheckUpdate> for FraudCheckUpdateInternal {
metadata,
modified_at: _,
last_step,
+ payment_capture_method,
} => Self {
frm_status: Some(frm_status),
frm_transaction_id,
@@ -96,6 +102,7 @@ impl From<FraudCheckUpdate> for FraudCheckUpdateInternal {
frm_score,
metadata,
last_step,
+ payment_capture_method,
..Default::default()
},
FraudCheckUpdate::ErrorUpdate {
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 603e0f4ebf2..65481d93bec 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -209,6 +209,7 @@ pub enum PaymentAttemptUpdate {
currency: storage_enums::Currency,
status: storage_enums::AttemptStatus,
authentication_type: Option<storage_enums::AuthenticationType>,
+ capture_method: Option<storage_enums::CaptureMethod>,
payment_method: Option<storage_enums::PaymentMethod>,
browser_info: Option<serde_json::Value>,
connector: Option<String>,
@@ -559,6 +560,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
amount,
currency,
authentication_type,
+ capture_method,
status,
payment_method,
browser_info,
@@ -610,6 +612,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
payment_method_billing_address_id,
fingerprint_id,
payment_method_id,
+ capture_method,
..Default::default()
},
PaymentAttemptUpdate::VoidUpdate {
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index d1711c8ba00..ee6e3960b73 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -180,6 +180,7 @@ pub enum PaymentIntentUpdate {
updated_by: String,
},
ApproveUpdate {
+ status: storage_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
@@ -456,9 +457,11 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
..Default::default()
},
PaymentIntentUpdate::ApproveUpdate {
+ status,
merchant_decision,
updated_by,
} => Self {
+ status: Some(status),
merchant_decision,
updated_by,
..Default::default()
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 44429cc4cad..e983b09ff21 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -450,6 +450,7 @@ diesel::table! {
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
+ payment_capture_method -> Nullable<CaptureMethod>,
}
}
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 0e3f67c051b..b62d3afd4a8 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -1,6 +1,7 @@
use std::fmt::Debug;
use api_models::{admin::FrmConfigs, enums as api_enums, payments::AdditionalPaymentData};
+use common_enums::CaptureMethod;
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface};
use router_env::{
@@ -26,11 +27,14 @@ use crate::{
utils as core_utils,
},
db::StorageInterface,
- routes::AppState,
+ routes::{app::ReqState, AppState},
services,
types::{
self as oss_types,
- api::{routing::FrmRoutingAlgorithm, Connector, FraudCheckConnectorData, Fulfillment},
+ api::{
+ fraud_check as frm_api, routing::FrmRoutingAlgorithm, Connector,
+ FraudCheckConnectorData, Fulfillment,
+ },
domain, fraud_check as frm_types,
storage::{
enums::{
@@ -94,6 +98,15 @@ where
.await?;
router_data.status = payment_data.payment_attempt.status;
+ if matches!(
+ frm_data.fraud_check.frm_transaction_type,
+ FraudCheckType::PreFrm
+ ) && matches!(
+ frm_data.fraud_check.last_step,
+ FraudCheckLastStep::CheckoutOrSale
+ ) {
+ frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund
+ }
let connector =
FraudCheckConnectorData::get_connector_by_name(&frm_data.connector_details.connector_name)?;
@@ -295,7 +308,7 @@ where
let is_frm_enabled =
is_frm_connector_enabled && is_frm_pm_enabled && is_frm_pmt_enabled;
logger::debug!(
- "frm_configs {:?} {:?} {:?} {:?}",
+ "is_frm_connector_enabled {:?}, is_frm_pm_enabled: {:?},is_frm_pmt_enabled : {:?}, is_frm_enabled :{:?}",
is_frm_connector_enabled,
is_frm_pm_enabled,
is_frm_pmt_enabled,
@@ -423,7 +436,7 @@ where
}
#[allow(clippy::too_many_arguments)]
-pub async fn pre_payment_frm_core<'a, F>(
+pub async fn pre_payment_frm_core<'a, F, Req, Ctx>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
payment_data: &mut payments::PaymentData<F>,
@@ -433,85 +446,108 @@ pub async fn pre_payment_frm_core<'a, F>(
should_continue_transaction: &mut bool,
should_continue_capture: &mut bool,
key_store: domain::MerchantKeyStore,
+ operation: &BoxedOperation<'_, F, Req, Ctx>,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
{
- if let Some(frm_data) = &mut frm_info.frm_data {
- if matches!(
- frm_configs.frm_preferred_flow_type,
- api_enums::FrmPreferredFlowTypes::Pre
- ) {
- let fraud_check_operation = &mut frm_info.fraud_check_operation;
+ let mut frm_data = None;
+ if is_operation_allowed(operation) {
+ frm_data = if let Some(frm_data) = &mut frm_info.frm_data {
+ if matches!(
+ frm_configs.frm_preferred_flow_type,
+ api_enums::FrmPreferredFlowTypes::Pre
+ ) {
+ let fraud_check_operation = &mut frm_info.fraud_check_operation;
- let frm_router_data = fraud_check_operation
- .to_domain()?
- .pre_payment_frm(
+ let frm_router_data = fraud_check_operation
+ .to_domain()?
+ .pre_payment_frm(
+ state,
+ payment_data,
+ frm_data,
+ merchant_account,
+ customer,
+ key_store.clone(),
+ )
+ .await?;
+ let _router_data = call_frm_service::<F, frm_api::Transaction, _>(
state,
payment_data,
frm_data,
merchant_account,
+ &key_store,
customer,
- key_store,
)
.await?;
- let frm_data_updated = fraud_check_operation
- .to_update_tracker()?
- .update_tracker(
- &*state.store,
- frm_data.clone(),
- payment_data,
- None,
- frm_router_data,
- )
- .await?;
- let frm_fraud_check = frm_data_updated.fraud_check.clone();
- payment_data.frm_message = Some(frm_fraud_check.clone());
- if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) {
- if matches!(frm_configs.frm_action, api_enums::FrmAction::CancelTxn) {
+ let frm_data_updated = fraud_check_operation
+ .to_update_tracker()?
+ .update_tracker(
+ &*state.store,
+ frm_data.clone(),
+ payment_data,
+ None,
+ frm_router_data,
+ )
+ .await?;
+ let frm_fraud_check = frm_data_updated.fraud_check.clone();
+ payment_data.frm_message = Some(frm_fraud_check.clone());
+ if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) {
*should_continue_transaction = false;
- frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction);
- } else if matches!(frm_configs.frm_action, api_enums::FrmAction::ManualReview) {
- *should_continue_capture = false;
- frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview);
+ if matches!(frm_configs.frm_action, api_enums::FrmAction::CancelTxn) {
+ frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction);
+ } else if matches!(frm_configs.frm_action, api_enums::FrmAction::ManualReview) {
+ *should_continue_capture = false;
+ frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview);
+ }
}
+ logger::debug!(
+ "frm_updated_data: {:?} {:?}",
+ frm_info.fraud_check_operation,
+ frm_info.suggested_action
+ );
+ Some(frm_data_updated)
+ } else if matches!(
+ frm_configs.frm_preferred_flow_type,
+ api_enums::FrmPreferredFlowTypes::Post
+ ) {
+ *should_continue_capture = false;
+ Some(frm_data.to_owned())
+ } else {
+ Some(frm_data.to_owned())
}
- logger::debug!(
- "frm_updated_data: {:?} {:?}",
- frm_info.fraud_check_operation,
- frm_info.suggested_action
- );
- Ok(Some(frm_data_updated))
} else {
- Ok(Some(frm_data.to_owned()))
- }
- } else {
- Ok(None)
+ None
+ };
}
+ Ok(frm_data)
}
#[allow(clippy::too_many_arguments)]
pub async fn post_payment_frm_core<'a, F>(
state: &AppState,
+ req_state: ReqState,
merchant_account: &domain::MerchantAccount,
payment_data: &mut payments::PaymentData<F>,
frm_info: &mut FrmInfo<F>,
frm_configs: FrmConfigsObject,
customer: &Option<domain::Customer>,
key_store: domain::MerchantKeyStore,
+ should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
{
if let Some(frm_data) = &mut frm_info.frm_data {
- // Allow the Post flow only if the payment is succeeded,
+ // Allow the Post flow only if the payment is authorized,
// this logic has to be removed if we are going to call /sale or /transaction after failed transaction
let fraud_check_operation = &mut frm_info.fraud_check_operation;
- if payment_data.payment_attempt.status == AttemptStatus::Charged {
+ if payment_data.payment_attempt.status == AttemptStatus::Authorized {
let frm_router_data_opt = fraud_check_operation
.to_domain()?
.post_payment_frm(
state,
+ req_state.clone(),
payment_data,
frm_data,
merchant_account,
@@ -530,18 +566,23 @@ where
frm_router_data.to_owned(),
)
.await?;
-
- payment_data.frm_message = Some(frm_data.fraud_check.clone());
- logger::debug!(
- "frm_updated_data: {:?} {:?}",
- frm_data,
- payment_data.frm_message
- );
+ let frm_fraud_check = frm_data.fraud_check.clone();
let mut frm_suggestion = None;
+ payment_data.frm_message = Some(frm_fraud_check.clone());
+ if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) {
+ if matches!(frm_configs.frm_action, api_enums::FrmAction::CancelTxn) {
+ frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction);
+ } else if matches!(frm_configs.frm_action, api_enums::FrmAction::ManualReview) {
+ frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview);
+ }
+ } else if matches!(frm_fraud_check.frm_status, FraudCheckStatus::ManualReview) {
+ frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview);
+ }
fraud_check_operation
.to_domain()?
.execute_post_tasks(
state,
+ req_state,
&mut frm_data,
merchant_account,
frm_configs,
@@ -549,6 +590,7 @@ where
key_store,
payment_data,
customer,
+ should_continue_capture,
)
.await?;
logger::debug!("frm_post_tasks_data: {:?}", frm_data);
@@ -588,51 +630,76 @@ pub async fn call_frm_before_connector_call<'a, F, Req, Ctx>(
where
F: Send + Clone,
{
- if is_operation_allowed(operation) {
- let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) =
- should_call_frm(merchant_account, payment_data, db, key_store.clone()).await?;
- if let Some((frm_routing_algorithm_val, profile_id)) =
- frm_routing_algorithm.zip(frm_connector_label)
- {
- if let Some(frm_configs) = frm_configs.clone() {
- let mut updated_frm_info = make_frm_data_and_fraud_check_operation(
- db,
+ let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) =
+ should_call_frm(merchant_account, payment_data, db, key_store.clone()).await?;
+ if let Some((frm_routing_algorithm_val, profile_id)) =
+ frm_routing_algorithm.zip(frm_connector_label)
+ {
+ if let Some(frm_configs) = frm_configs.clone() {
+ let mut updated_frm_info = make_frm_data_and_fraud_check_operation(
+ db,
+ state,
+ merchant_account,
+ payment_data.to_owned(),
+ frm_routing_algorithm_val,
+ profile_id,
+ frm_configs.clone(),
+ customer,
+ )
+ .await?;
+
+ if is_frm_enabled {
+ pre_payment_frm_core(
state,
merchant_account,
- payment_data.to_owned(),
- frm_routing_algorithm_val,
- profile_id,
- frm_configs.clone(),
+ payment_data,
+ &mut updated_frm_info,
+ frm_configs,
customer,
+ should_continue_transaction,
+ should_continue_capture,
+ key_store,
+ operation,
)
.await?;
-
- if is_frm_enabled {
- pre_payment_frm_core(
- state,
- merchant_account,
- payment_data,
- &mut updated_frm_info,
- frm_configs,
- customer,
- should_continue_transaction,
- should_continue_capture,
- key_store,
- )
- .await?;
- }
- *frm_info = Some(updated_frm_info);
}
+ *frm_info = Some(updated_frm_info);
}
- logger::debug!("frm_configs: {:?} {:?}", frm_configs, is_frm_enabled);
- return Ok(frm_configs);
}
- Ok(None)
+ let fraud_capture_method = frm_info.as_ref().and_then(|frm_info| {
+ frm_info
+ .frm_data
+ .as_ref()
+ .map(|frm_data| frm_data.fraud_check.payment_capture_method)
+ });
+ if matches!(fraud_capture_method, Some(Some(CaptureMethod::Manual)))
+ && matches!(
+ payment_data.payment_attempt.status,
+ api_models::enums::AttemptStatus::Unresolved
+ )
+ {
+ if let Some(info) = frm_info {
+ info.suggested_action = Some(FrmSuggestion::FrmAuthorizeTransaction)
+ };
+ *should_continue_transaction = false;
+ logger::debug!(
+ "skipping connector call since payment_capture_method is already {:?}",
+ fraud_capture_method
+ );
+ };
+ logger::debug!("frm_configs: {:?} {:?}", frm_configs, is_frm_enabled);
+ Ok(frm_configs)
}
pub fn is_operation_allowed<Op: Debug>(operation: &Op) -> bool {
- !["PaymentSession", "PaymentApprove", "PaymentReject"]
- .contains(&format!("{operation:?}").as_str())
+ ![
+ "PaymentSession",
+ "PaymentApprove",
+ "PaymentReject",
+ "PaymentCapture",
+ "PaymentsCancel",
+ ]
+ .contains(&format!("{operation:?}").as_str())
}
impl From<PaymentToFrmData> for PaymentDetails {
@@ -759,6 +826,7 @@ pub async fn make_fulfillment_api_call(
metadata: fraud_check.metadata,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Fulfillment,
+ payment_capture_method: fraud_check.payment_capture_method,
};
let _updated = db
.update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update)
diff --git a/crates/router/src/core/fraud_check/operation.rs b/crates/router/src/core/fraud_check/operation.rs
index e7677dad6f3..a9b95cdf3b5 100644
--- a/crates/router/src/core/fraud_check/operation.rs
+++ b/crates/router/src/core/fraud_check/operation.rs
@@ -15,7 +15,7 @@ use crate::{
payments,
},
db::StorageInterface,
- routes::AppState,
+ routes::{app::ReqState, AppState},
types::{domain, fraud_check::FrmRouterData},
};
@@ -47,10 +47,12 @@ pub trait GetTracker<D>: Send {
}
#[async_trait]
+#[allow(clippy::too_many_arguments)]
pub trait Domain<F>: Send + Sync {
async fn post_payment_frm<'a>(
&'a self,
state: &'a AppState,
+ req_state: ReqState,
payment_data: &mut payments::PaymentData<F>,
frm_data: &mut FrmData,
merchant_account: &domain::MerchantAccount,
@@ -78,6 +80,7 @@ pub trait Domain<F>: Send + Sync {
async fn execute_post_tasks(
&self,
_state: &AppState,
+ _req_state: ReqState,
frm_data: &mut FrmData,
_merchant_account: &domain::MerchantAccount,
_frm_configs: FrmConfigsObject,
@@ -85,6 +88,7 @@ pub trait Domain<F>: Send + Sync {
_key_store: domain::MerchantKeyStore,
_payment_data: &mut payments::PaymentData<F>,
_customer: &Option<domain::Customer>,
+ _should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index a6cd0976129..d59c8c5ff47 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -1,5 +1,6 @@
+use api_models::payments::HeaderPayload;
use async_trait::async_trait;
-use common_enums::FrmSuggestion;
+use common_enums::{CaptureMethod, FrmSuggestion};
use common_utils::ext_traits::Encode;
use data_models::payments::{
payment_attempt::PaymentAttemptUpdate, payment_intent::PaymentIntentUpdate,
@@ -13,18 +14,20 @@ use crate::{
errors::{RouterResult, StorageErrorExt},
fraud_check::{
self as frm_core,
- types::{FrmData, PaymentDetails, PaymentToFrmData, REFUND_INITIATED},
+ types::{FrmData, PaymentDetails, PaymentToFrmData, CANCEL_INITIATED},
ConnectorDetailsCore, FrmConfigsObject,
},
- payments, refunds,
+ payment_methods::Oss,
+ payments,
},
db::StorageInterface,
- errors, services,
+ errors,
+ routes::app::ReqState,
+ services::{self, api},
types::{
api::{
enums::{AttemptStatus, FrmAction, IntentStatus},
- fraud_check as frm_api,
- refunds::{RefundRequest, RefundType},
+ fraud_check as frm_api, payments as payment_types, Capture, Void,
},
domain,
fraud_check::{
@@ -107,6 +110,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost {
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
+ payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
@@ -140,6 +144,7 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost {
async fn post_payment_frm<'a>(
&'a self,
state: &'a AppState,
+ _req_state: ReqState,
payment_data: &mut payments::PaymentData<F>,
frm_data: &mut FrmData,
merchant_account: &domain::MerchantAccount,
@@ -177,6 +182,7 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost {
async fn execute_post_tasks(
&self,
state: &AppState,
+ req_state: ReqState,
frm_data: &mut FrmData,
merchant_account: &domain::MerchantAccount,
frm_configs: FrmConfigsObject,
@@ -184,38 +190,47 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost {
key_store: domain::MerchantKeyStore,
payment_data: &mut payments::PaymentData<F>,
customer: &Option<domain::Customer>,
+ _should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>> {
if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Fraud)
- && matches!(frm_configs.frm_action, FrmAction::AutoRefund)
+ && matches!(frm_configs.frm_action, FrmAction::CancelTxn)
&& matches!(
frm_data.fraud_check.last_step,
FraudCheckLastStep::CheckoutOrSale
)
{
- *frm_suggestion = Some(FrmSuggestion::FrmAutoRefund);
- let ref_req = RefundRequest {
- refund_id: None,
- payment_id: payment_data.payment_intent.payment_id.clone(),
- merchant_id: Some(merchant_account.merchant_id.clone()),
- amount: None,
- reason: frm_data
- .fraud_check
- .frm_reason
- .clone()
- .map(|data| data.to_string()),
- refund_type: Some(RefundType::Instant),
- metadata: None,
+ *frm_suggestion = Some(FrmSuggestion::FrmCancelTransaction);
+
+ let cancel_req = api_models::payments::PaymentsCancelRequest {
+ payment_id: frm_data.payment_intent.payment_id.clone(),
+ cancellation_reason: frm_data.fraud_check.frm_error.clone(),
merchant_connector_details: None,
};
- let refund = Box::pin(refunds::refund_create_core(
+ let cancel_res = Box::pin(payments::payments_core::<
+ Void,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
state.clone(),
+ req_state.clone(),
merchant_account.clone(),
key_store.clone(),
- ref_req,
+ payments::PaymentCancel,
+ cancel_req,
+ api::AuthFlow::Merchant,
+ payments::CallConnectorAction::Trigger,
+ None,
+ HeaderPayload::default(),
))
.await?;
- if let services::ApplicationResponse::Json(new_refund) = refund {
- frm_data.refund = Some(new_refund);
+ logger::debug!("payment_id : {:?} has been cancelled since it has been found fraudulent by configured frm connector",payment_data.payment_attempt.payment_id);
+ if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
+ cancel_res
+ {
+ payment_data.payment_intent.status = payments_response.status;
}
let _router_data = frm_core::call_frm_service::<F, frm_api::RecordReturn, _>(
state,
@@ -227,6 +242,51 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPost {
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
+ } else if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Fraud)
+ && matches!(frm_configs.frm_action, FrmAction::ManualReview)
+ {
+ *frm_suggestion = Some(FrmSuggestion::FrmManualReview);
+ } else if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Legit)
+ && matches!(
+ frm_data.fraud_check.payment_capture_method,
+ Some(CaptureMethod::Automatic)
+ )
+ {
+ let capture_request = api_models::payments::PaymentsCaptureRequest {
+ payment_id: frm_data.payment_intent.payment_id.clone(),
+ merchant_id: None,
+ amount_to_capture: None,
+ refund_uncaptured_amount: None,
+ statement_descriptor_suffix: None,
+ statement_descriptor_prefix: None,
+ merchant_connector_details: None,
+ };
+ let capture_response = Box::pin(payments::payments_core::<
+ Capture,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
+ state.clone(),
+ req_state.clone(),
+ merchant_account.clone(),
+ key_store.clone(),
+ payments::PaymentCapture,
+ capture_request,
+ api::AuthFlow::Merchant,
+ payments::CallConnectorAction::Trigger,
+ None,
+ HeaderPayload::default(),
+ ))
+ .await?;
+ logger::debug!("payment_id : {:?} has been captured since it has been found legit by configured frm connector",payment_data.payment_attempt.payment_id);
+ if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
+ capture_response
+ {
+ payment_data.payment_intent.status = payments_response.status;
+ }
};
return Ok(Some(frm_data.to_owned()));
}
@@ -302,6 +362,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost {
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
+ payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
},
@@ -346,6 +407,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost {
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
+ payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
@@ -396,6 +458,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost {
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
+ payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
@@ -412,15 +475,27 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost {
}
};
- if frm_suggestion == Some(FrmSuggestion::FrmAutoRefund) {
+ if let Some(frm_suggestion) = frm_suggestion {
+ let (payment_attempt_status, payment_intent_status) = match frm_suggestion {
+ FrmSuggestion::FrmCancelTransaction => {
+ (AttemptStatus::Failure, IntentStatus::Failed)
+ }
+ FrmSuggestion::FrmManualReview => (
+ AttemptStatus::Unresolved,
+ IntentStatus::RequiresMerchantAction,
+ ),
+ FrmSuggestion::FrmAuthorizeTransaction => {
+ (AttemptStatus::Authorized, IntentStatus::RequiresCapture)
+ }
+ };
payment_data.payment_attempt = db
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
PaymentAttemptUpdate::RejectUpdate {
- status: AttemptStatus::Failure,
+ status: payment_attempt_status,
error_code: Some(Some(frm_data.fraud_check.frm_status.to_string())),
- error_message: Some(Some(REFUND_INITIATED.to_string())),
- updated_by: frm_data.merchant_account.storage_scheme.to_string(), // merchant_decision: Some(MerchantDecision::AutoRefunded),
+ error_message: Some(Some(CANCEL_INITIATED.to_string())),
+ updated_by: frm_data.merchant_account.storage_scheme.to_string(),
},
frm_data.merchant_account.storage_scheme,
)
@@ -431,8 +506,8 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPost {
.update_payment_intent(
payment_data.payment_intent.clone(),
PaymentIntentUpdate::RejectUpdate {
- status: IntentStatus::Failed,
- merchant_decision: Some(MerchantDecision::AutoRefunded.to_string()),
+ status: payment_intent_status,
+ merchant_decision: Some(MerchantDecision::Rejected.to_string()),
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
},
frm_data.merchant_account.storage_scheme,
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
index ed582574bf5..eac8dc84da5 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
@@ -18,6 +18,7 @@ use crate::{
},
db::StorageInterface,
errors,
+ routes::app::ReqState,
types::{
api::fraud_check as frm_api,
domain,
@@ -104,6 +105,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
+ payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
@@ -138,6 +140,7 @@ impl<F: Send + Clone> Domain<F> for FraudCheckPre {
async fn post_payment_frm<'a>(
&'a self,
state: &'a AppState,
+ _req_state: ReqState,
payment_data: &mut payments::PaymentData<F>,
frm_data: &mut FrmData,
merchant_account: &domain::MerchantAccount,
@@ -248,6 +251,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPre {
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
+ payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
@@ -300,6 +304,7 @@ impl<F: Clone + Send> UpdateTracker<FrmData, F> for FraudCheckPre {
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
+ payment_capture_method: None,
};
Some(fraud_check_update)
}
diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs
index e60458646f3..46a341142f7 100644
--- a/crates/router/src/core/fraud_check/types.rs
+++ b/crates/router/src/core/fraud_check/types.rs
@@ -215,4 +215,4 @@ pub struct FrmFulfillmentSignifydApiResponse {
pub shipment_ids: Vec<String>,
}
-pub const REFUND_INITIATED: &str = "Refund Initiated with the processor";
+pub const CANCEL_INITIATED: &str = "Cancel Initiated with the processor";
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 2eb080f952c..416ec38e577 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -222,7 +222,7 @@ where
};
#[cfg(feature = "frm")]
logger::debug!(
- "frm_configs: {:?}\nshould_cancel_transaction: {:?}\nshould_continue_capture: {:?}",
+ "frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}",
frm_configs,
should_continue_transaction,
should_continue_capture,
@@ -239,7 +239,6 @@ where
&key_store,
)
.await?;
-
if should_continue_transaction {
#[cfg(feature = "frm")]
match (
@@ -248,8 +247,15 @@ where
) {
(false, Some(storage_enums::CaptureMethod::Automatic))
| (false, Some(storage_enums::CaptureMethod::Scheduled)) => {
+ if let Some(info) = &mut frm_info {
+ if let Some(frm_data) = &mut info.frm_data {
+ frm_data.fraud_check.payment_capture_method =
+ payment_data.payment_attempt.capture_method;
+ }
+ }
payment_data.payment_attempt.capture_method =
Some(storage_enums::CaptureMethod::Manual);
+ logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.payment_attempt.payment_id);
}
_ => (),
};
@@ -270,7 +276,7 @@ where
};
let router_data = call_connector_service(
state,
- req_state,
+ req_state.clone(),
&merchant_account,
&key_store,
connector.clone(),
@@ -370,7 +376,7 @@ where
if config_bool && router_data.should_call_gsm() {
router_data = retry::do_gsm_actions(
state,
- req_state,
+ req_state.clone(),
&mut payment_data,
connectors,
connector_data.clone(),
@@ -446,6 +452,7 @@ where
if let Some(fraud_info) = &mut frm_info {
Box::pin(frm_core::post_payment_frm_core(
state,
+ req_state,
&merchant_account,
&mut payment_data,
fraud_info,
@@ -457,6 +464,7 @@ where
.attach_printable("Frm configs label not found")?,
&customer,
key_store.clone(),
+ &mut should_continue_capture,
))
.await?;
}
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index be73d0836dd..bc82474f7e5 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -1,6 +1,6 @@
use std::marker::PhantomData;
-use api_models::enums::FrmSuggestion;
+use api_models::enums::{AttemptStatus, FrmSuggestion, IntentStatus};
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
@@ -206,7 +206,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_merchant_key_store: &domain::MerchantKeyStore,
- _frm_suggestion: Option<FrmSuggestion>,
+ frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
@@ -215,7 +215,12 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
where
F: 'b + Send,
{
+ if matches!(frm_suggestion, Some(FrmSuggestion::FrmAuthorizeTransaction)) {
+ payment_data.payment_intent.status = IntentStatus::RequiresCapture; // In Approve flow, payment which has payment_capture_method "manual" and attempt status as "Unresolved",
+ payment_data.payment_attempt.status = AttemptStatus::Authorized; // We shouldn't call the connector instead we need to update the payment attempt and payment intent.
+ }
let intent_status_update = storage::PaymentIntentUpdate::ApproveUpdate {
+ status: payment_data.payment_intent.status,
merchant_decision: Some(api_models::enums::MerchantDecision::Approved.to_string()),
updated_by: storage_scheme.to_string(),
};
@@ -228,6 +233,17 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ db.store
+ .update_payment_attempt_with_attempt_id(
+ payment_data.payment_attempt.clone(),
+ storage::PaymentAttemptUpdate::StatusUpdate {
+ status: payment_data.payment_attempt.status,
+ updated_by: storage_scheme.to_string(),
+ },
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok((Box::new(self), payment_data))
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index de0e6604098..4a096620e7f 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -922,6 +922,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
let payment_method = payment_data.payment_attempt.payment_method;
let browser_info = payment_data.payment_attempt.browser_info.clone();
let frm_message = payment_data.frm_message.clone();
+ let capture_method = payment_data.payment_attempt.capture_method;
let default_status_result = (
storage_enums::IntentStatus::Processing,
@@ -944,7 +945,11 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
storage_enums::AttemptStatus::Unresolved,
(None, None),
),
- FrmSuggestion::FrmAutoRefund => default_status_result.clone(),
+ FrmSuggestion::FrmAuthorizeTransaction => (
+ storage_enums::IntentStatus::RequiresCapture,
+ storage_enums::AttemptStatus::Authorized,
+ (None, None),
+ ),
};
let status_handler_for_authentication_results =
@@ -1037,6 +1042,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
let m_browser_info = browser_info.clone();
let m_connector = connector.clone();
+ let m_capture_method = capture_method;
let m_payment_token = payment_token.clone();
let m_additional_pm_data = additional_pm_data.clone();
let m_business_sub_label = business_sub_label.clone();
@@ -1077,6 +1083,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
status: attempt_status,
payment_method,
authentication_type,
+ capture_method: m_capture_method,
browser_info: m_browser_info,
connector: m_connector,
payment_token: m_payment_token,
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 85ef0cfe6b7..2d4b34b30d5 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -849,6 +849,7 @@ where
enums::IntentStatus::Succeeded
| enums::IntentStatus::Failed
| enums::IntentStatus::PartiallyCaptured
+ | enums::IntentStatus::RequiresMerchantAction
) {
let payments_response = crate::core::payments::transformers::payments_to_payments_response(
payment_data,
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 1fd25f3dedb..683b0469a2a 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1445,6 +1445,7 @@ impl DataModelExt for PaymentAttemptUpdate {
currency,
status,
authentication_type,
+ capture_method,
payment_method,
browser_info,
connector,
@@ -1472,6 +1473,7 @@ impl DataModelExt for PaymentAttemptUpdate {
currency,
status,
authentication_type,
+ capture_method,
payment_method,
browser_info,
connector,
@@ -1744,6 +1746,7 @@ impl DataModelExt for PaymentAttemptUpdate {
currency,
status,
authentication_type,
+ capture_method,
payment_method,
browser_info,
connector,
@@ -1771,6 +1774,7 @@ impl DataModelExt for PaymentAttemptUpdate {
currency,
status,
authentication_type,
+ capture_method,
payment_method,
browser_info,
connector,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 6b4cf8b82e1..4d984a02cc9 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -1113,9 +1113,11 @@ impl DataModelExt for PaymentIntentUpdate {
updated_by,
},
Self::ApproveUpdate {
+ status,
merchant_decision,
updated_by,
} => DieselPaymentIntentUpdate::ApproveUpdate {
+ status,
merchant_decision,
updated_by,
},
diff --git a/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/down.sql b/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/down.sql
new file mode 100644
index 00000000000..596fb1022fd
--- /dev/null
+++ b/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE fraud_check
+DROP COLUMN IF EXISTS payment_capture_method;
\ No newline at end of file
diff --git a/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/up.sql b/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/up.sql
new file mode 100644
index 00000000000..08e89a49c11
--- /dev/null
+++ b/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE fraud_check
+ADD COLUMN IF NOT EXISTS payment_capture_method "CaptureMethod" NULL;
\ No newline at end of file
|
2024-04-18T11:47: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 -->
PostAuth flow
- The underlying FRM connector is invoked post authentication of the user from the bank.
- If a transaction’s capture method was set to automatic, it is updated to manual for avoiding automatic capture.
- Once the user completes the authentication, the underlying FRM connector is invoked. The decision whether or not to
proceed with the txn is based on the status / score returned.
**Possible actions based on the status**
- Continue on **Accept**
- Continue with the **transaction**
- Halt on **Decline**
- Mark the transaction as cancelled
- Approve / Decline on **Manual Review**
- Hold the txn in manual review state. Merchants can list and review such transactions.
- If approved, payment is captured
- If declined, payment is voided
This flow works same as payments flow incase of 3ds, non 3ds, manual and auto capture for **Legit** payments.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
up.sql
```
ALTER TABLE fraud_check
ADD COLUMN IF NOT EXISTS payment_capture_method "CaptureMethod" NULL;
```
down.sql
```
ALTER TABLE fraud_check
DROP COLUMN IF EXISTS payment_capture_method;
```
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Create merchant connector account with stripe and then create new merchant connector account with signifyd.
```
{
"connector_type": "payment_VAS",
"connector_name": "signifyd",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "YOUR_API_KEY"
},
"test_mode": false,
"disabled": false,
"business_country": "US",
"business_label": "default",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245"
},
"frm_configs": [
{
"gateway": "stripe",
"payment_methods": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa"
],
"flow": "post",
"action": "cancel_txn"
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa"
],
"flow": "post",
"action": "manual_review"
}
]
}
]
}
]
}
```
**TEST CASE 1 :** Create legit card payment(amount =150) for both credit and debit. This should go as normal payment flow. Interchange CaptureMethod and CardType(3ds, non 3ds).
**TEST CASE 2 :** Create Credit(pmt type) Payment with amount equals to 15000. This should Fail the payment .
```
{
"amount": 15000,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 1500,
"customer_id": "StripeCustomer2",
"email": "guest@example.com",
"name": "Bob Smith",
"phone": "999999999",
"phone_country_code": "+91",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "31 Sherwood Gardens",
"line3": "31 Sherwood Gardens",
"city": "London",
"state": "Manchester",
"zip": "E14 9wn",
"country": "GB",
"first_name": "Bob",
"last_name": "Smith"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"order_details" : [{
"product_name" : "gillete creme",
"quantity" : 2,
"amount" : 600
},
{
"product_name" : "gillete razor",
"quantity" : 1,
"amount" : 300
}]
}
```
**TESTCASE 3** : Create a payment with payment method type as `debit`. set capture method to `automatic` and use same json above. Payment status should be moved to `RequiresMerchantAction`.
Response looks like this
```
{
"payment_id": "pay_9ZgUMXOiLv35wrF6oOyd",
"merchant_id": "merchant_1713525778",
"status": "requires_merchant_action",
"amount": 150000,
"net_amount": 150000,
"amount_capturable": 150000,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_9ZgUMXOiLv35wrF6oOyd_secret_wU5hfAMsYjBe0fXepJmj",
"created": "2024-04-19T11:58:40.749Z",
"currency": "USD",
"customer_id": "StripeCustomer2",
"customer": {
"id": "StripeCustomer2",
"name": "Bob Smith",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+91"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"cvc_check": "pass",
"address_line1_check": "pass",
"address_postal_code_check": "pass"
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "London",
"country": "GB",
"line1": "1467",
"line2": "31 Sherwood Gardens",
"line3": "31 Sherwood Gardens",
"zip": "E14 9wn",
"state": "Manchester",
"first_name": "Bob",
"last_name": "Smith"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": [
{
"brand": null,
"amount": 600,
"category": null,
"quantity": 2,
"product_id": null,
"product_name": "gillete creme",
"product_type": null,
"product_img_link": null,
"requires_shipping": null
},
{
"brand": null,
"amount": 300,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "gillete razor",
"product_type": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "Bob Smith",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": "fraud",
"error_message": "Refund Initiated with the processor",
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer2",
"created_at": 1713527920,
"expires": 1713531520,
"secret": "epk_22d24f1ef64b44a0b28b72a81c2b2392"
},
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3P7G5VD5R7gDAGff0XEZqQkO",
"frm_message": {
"frm_name": "signifyd",
"frm_transaction_id": "pay_9ZgUMXOiLv35wrF6oOyd_1",
"frm_transaction_type": "post_frm",
"frm_status": "fraud",
"frm_score": 497,
"frm_reason": "SIGNIFYD_DECLINED",
"frm_error": null
},
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P7G5VD5R7gDAGff0XEZqQkO",
"payment_link": null,
"profile_id": "pro_DOE6fPp88zY1M4xUyO0H",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_U0XVEDfTM0JMpiv9GOr5",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-19T12:13:40.749Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-04-19T11:58:41.929Z"
}
```
`/approve` and `/reject` should hit after above step for the same payment which will mark payment as succeeded and failed by merchant.
Request curl :
```
curl --location --request POST 'http://localhost:8080/payments/{{payment_id}}/approve' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{}'
```
Response json :
```
{
"payment_id": "pay_9ZgUMXOiLv35wrF6oOyd",
"merchant_id": "merchant_1713525778",
"status": "succeeded",
"amount": 150000,
"net_amount": 150000,
"amount_capturable": 0,
"amount_received": 150000,
"connector": "stripe",
"client_secret": "pay_9ZgUMXOiLv35wrF6oOyd_secret_wU5hfAMsYjBe0fXepJmj",
"created": "2024-04-19T11:58:40.749Z",
"currency": "USD",
"customer_id": "StripeCustomer2",
"customer": {
"id": "StripeCustomer2",
"name": "Bob Smith",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+91"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"cvc_check": "pass",
"address_line1_check": "pass",
"address_postal_code_check": "pass"
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "London",
"country": "GB",
"line1": "1467",
"line2": "31 Sherwood Gardens",
"line3": "31 Sherwood Gardens",
"zip": "E14 9wn",
"state": "Manchester",
"first_name": "Bob",
"last_name": "Smith"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": [
{
"brand": null,
"amount": 600,
"category": null,
"quantity": 2,
"product_id": null,
"product_name": "gillete creme",
"product_type": null,
"product_img_link": null,
"requires_shipping": null
},
{
"brand": null,
"amount": 300,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "gillete razor",
"product_type": null,
"product_img_link": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "Bob Smith",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3P7G5VD5R7gDAGff0XEZqQkO",
"frm_message": {
"frm_name": "signifyd",
"frm_transaction_id": "pay_9ZgUMXOiLv35wrF6oOyd_1",
"frm_transaction_type": "post_frm",
"frm_status": "fraud",
"frm_score": 497,
"frm_reason": "SIGNIFYD_DECLINED",
"frm_error": null
},
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P7G5VD5R7gDAGff0XEZqQkO",
"payment_link": null,
"profile_id": "pro_DOE6fPp88zY1M4xUyO0H",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": "approved",
"merchant_connector_id": "mca_U0XVEDfTM0JMpiv9GOr5",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-19T12:13:40.749Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-04-19T12:01:50.944Z"
}
```
## Checklist
<!-- Put an `x` in 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
|
cbf7cf4fcfcfe5a993c88bfc49ef6e284046524b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4381
|
Bug: docs(cypress): Update Cypress README Documentation
### Feature Description
In this PR, I have updated the README file to include detailed information about Cypress test scenarios and the folder structure .
Added detailed instructions for adding new test scenarios to the ConnectorTest directory.
Included a clear explanation of the folder structure, guiding contributors on where to find specific files and directories related to Cypress tests.
Emphasized the importance of writing clear test scenarios using Cypress commands for effective testing.
By providing a descriptive title and detailed description, reviewers can quickly understand the purpose of the changes and ensure that the README file enhancements align with the project's goals and standards.
### Possible Implementation
In this PR, I have updated the README file to include detailed information about Cypress test scenarios and the folder structure .
Added detailed instructions for adding new test scenarios to the ConnectorTest directory.
Included a clear explanation of the folder structure, guiding contributors on where to find specific files and directories related to Cypress tests.
Emphasized the importance of writing clear test scenarios using Cypress commands for effective testing.
By providing a descriptive title and detailed description, reviewers can quickly understand the purpose of the changes and ensure that the README file enhancements align with the project's goals and standards.
### 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!
|
2024-04-17T10:21:19Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
In this PR, I have updated the README file to include detailed information about Cypress test scenarios and the folder structure .
Added detailed instructions for adding new test scenarios to the ConnectorTest directory.
Included a clear explanation of the folder structure, guiding contributors on where to find specific files and directories related to Cypress tests.
Emphasized the importance of writing clear test scenarios using Cypress commands for effective testing.
By providing a descriptive title and detailed description, reviewers can quickly understand the purpose of the changes and ensure that the README file enhancements align with the project's goals and standards.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
This update aims to improve the documentation for contributors and provide a clearer understanding of the testing approach.
## 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
|
ca47ea9b13ff29085f7cc4e408f2b6498b1d6e8a
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4378
|
Bug: [Fix] 3DS mandates, for the connector _mandate_details to be stored in the payment_methods table
### Feature Description
After complete_authorize, or Psync the connector_mandate_details wasn't getting stored in the PaymentMethods table. Hence the recurringMandate would fail with the error Payment Methods not found
In this PR , we fix the 3ds mandate payments
### Possible Implementation
Add validations for such
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6e8e4e11fdd..48a6d411780 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -417,6 +417,7 @@ pub async fn get_token_pm_type_mandate_details(
mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
+ payment_method_id: Option<String>,
) -> RouterResult<MandateGenericData> {
let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from);
let (
@@ -529,15 +530,27 @@ pub async fn get_token_pm_type_mandate_details(
}
}
}
- None => (
- request.payment_token.to_owned(),
- request.payment_method,
- request.payment_method_type,
- mandate_data,
- None,
- None,
- None,
- ),
+ None => {
+ let payment_method_info = payment_method_id
+ .async_map(|payment_method_id| async move {
+ state
+ .store
+ .find_payment_method(&payment_method_id, merchant_account.storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
+ })
+ .await
+ .transpose()?;
+ (
+ request.payment_token.to_owned(),
+ request.payment_method,
+ request.payment_method_type,
+ mandate_data,
+ None,
+ None,
+ payment_method_info,
+ )
+ }
};
Ok(MandateGenericData {
token: payment_token,
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 e9e0ec36a73..89bdd0b84cc 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -119,6 +119,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_type.to_owned(),
merchant_account,
key_store,
+ payment_attempt.payment_method_id.clone(),
)
.await?;
let token = token.or_else(|| payment_attempt.payment_token.clone());
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 7af7e13b9fc..de0e6604098 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -484,6 +484,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
m_mandate_type,
&m_merchant_account,
&m_key_store,
+ None,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 99a387fc8d1..5d510f2afd4 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -134,6 +134,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_type.clone(),
merchant_account,
merchant_key_store,
+ None,
)
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 9bb8119d40c..b96cf483236 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -17,7 +17,7 @@ use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
mandate,
- payment_methods::PaymentMethodRetrieve,
+ payment_methods::{self, PaymentMethodRetrieve},
payments::{
self,
helpers::{
@@ -886,6 +886,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.in_current_span(),
);
+ // When connector requires redirection for mandate creation it can update the connector mandate_id in payment_methods during Psync and CompleteAuthorize
+
let flow_name = core_utils::get_flow_name::<F>()?;
if flow_name == "PSync" || flow_name == "CompleteAuthorize" {
let connector_mandate_id = match router_data.response.clone() {
@@ -904,23 +906,31 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
},
Err(_) => None,
};
- if let Some(ref payment_method) = payment_data.payment_method_info {
- payments::tokenization::update_connector_mandate_details_in_payment_method(
+ if let Some(payment_method) = payment_data.payment_method_info.clone() {
+ let connector_mandate_details =
+ payments::tokenization::update_connector_mandate_details_in_payment_method(
+ payment_method.clone(),
+ payment_method.payment_method_type,
+ Some(payment_data.payment_attempt.amount),
+ payment_data.payment_attempt.currency,
+ payment_data.payment_attempt.merchant_connector_id.clone(),
+ connector_mandate_id,
+ )?;
+ payment_methods::cards::update_payment_method_connector_mandate_details(
+ &*state.store,
payment_method.clone(),
- payment_method.payment_method_type,
- Some(payment_data.payment_attempt.amount),
- payment_data.payment_attempt.currency,
- payment_data.payment_attempt.merchant_connector_id.clone(),
- connector_mandate_id,
+ connector_mandate_details,
+ storage_scheme,
)
- .await?;
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?
}
}
-
// When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize
let m_db = state.clone().store;
- let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
let m_router_data_merchant_id = router_data.merchant_id.clone();
+ let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
let m_payment_data_mandate_id =
payment_data
.payment_attempt
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index bfd056e8f97..b201453068b 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -146,6 +146,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_type.to_owned(),
merchant_account,
key_store,
+ None,
)
.await?;
helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index c6f6a23d0a2..62acfb449eb 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -282,8 +282,7 @@ where
currency,
connector.merchant_connector_id.clone(),
connector_mandate_id.clone(),
- )
- .await?;
+ )?;
payment_methods::cards::update_payment_method_connector_mandate_details(db, pm, connector_mandate_details, merchant_account.storage_scheme).await.change_context(
errors::ApiErrorResponse::InternalServerError,
@@ -373,8 +372,7 @@ where
currency,
connector.merchant_connector_id.clone(),
connector_mandate_id.clone(),
- )
- .await?;
+ )?;
payment_methods::cards::update_payment_method_connector_mandate_details(db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme).await.change_context(
errors::ApiErrorResponse::InternalServerError,
@@ -809,7 +807,7 @@ pub fn add_connector_mandate_details_in_payment_method(
}
}
-pub async fn update_connector_mandate_details_in_payment_method(
+pub fn update_connector_mandate_details_in_payment_method(
payment_method: diesel_models::PaymentMethod,
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
@@ -866,5 +864,6 @@ pub async fn update_connector_mandate_details_in_payment_method(
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
+
Ok(connector_mandate_details)
}
|
2024-04-08T06:09:41Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
After complete_authorize, or Psync the connector_mandate_details wasn't getting stored in the PaymentMethods table. Hence the recurringMandate would fail with the error `Payment Methods not found`
In this PR , we fix the 3ds mandate payments
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a 3DS off-session payment/
- > `Create`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_njRmxwKH6ktMs37HQLB07DhgK1sFgROrpNiUiUgiSKyIzpoz3Wa5vKDCWc6PQlLe' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c77",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
-> `Confirm`
```
curl --location 'http://localhost:8080/payments/pay_UvTYFgVG2EelieqJlHZu/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_njRmxwKH6ktMs37HQLB07DhgK1sFgROrpNiUiUgiSKyIzpoz3Wa5vKDCWc6PQlLe' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}}
}'
```
- Make a recurring `off_Session:true` payment
- > `Create`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_njRmxwKH6ktMs37HQLB07DhgK1sFgROrpNiUiUgiSKyIzpoz3Wa5vKDCWc6PQlLe' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": true,
"customer_id": "new-c77",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"off_session":true,
"recurring_details":{
"type":"payment_method_id",
"data":"pm_SrFlrDpRmqb9ObWTB4E6"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
> `Response`
```
{
"payment_id": "pay_Kr0zqnLF7YvlfGambRdv",
"merchant_id": "merchant_1712557617",
"status": "succeeded",
"amount": 1000,
"net_amount": 1000,
"amount_capturable": 0,
"amount_received": 1000,
"connector": "cybersource",
"client_secret": "pay_Kr0zqnLF7YvlfGambRdv_secret_1g5i4yaC24q3cryBXRaH",
"created": "2024-04-08T06:33:18.853Z",
"currency": "USD",
"customer_id": "new-c77",
"customer": {
"id": "new-c77",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "new-c77",
"created_at": 1712557998,
"expires": 1712561598,
"secret": "epk_f0f3118f76554bc0862a93601aa6b628"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7125580011196185103955",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_Kr0zqnLF7YvlfGambRdv_1",
"payment_link": null,
"profile_id": "pro_WiTyPlqeoWjRO22EiiNb",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_cwp0jm7FkjSYWpeXVkG0",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-08T06:48:18.853Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_SrFlrDpRmqb9ObWTB4E6",
"payment_method_status": "active"
}
```
## Checklist
<!-- Put 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
|
ea0bc1e3f3f9a59531266db4c28c1d0c14ca9075
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4359
|
Bug: [FIX] Add onboarding_survey enum in dashboard metadata type
|
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs
index 66831c7aeb8..b547a61d450 100644
--- a/crates/api_models/src/user/dashboard_metadata.rs
+++ b/crates/api_models/src/user/dashboard_metadata.rs
@@ -26,6 +26,7 @@ pub enum SetMetaDataRequest {
IsMultipleConfiguration,
#[serde(skip)]
IsChangePasswordRequired,
+ OnboardingSurvey(OnboardingSurvey),
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -46,6 +47,20 @@ pub struct ProcessorConnected {
pub processor_name: String,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct OnboardingSurvey {
+ pub designation: Option<String>,
+ pub about_business: Option<String>,
+ pub business_website: Option<String>,
+ pub hyperswitch_req: Option<String>,
+ pub major_markets: Option<Vec<String>>,
+ pub business_size: Option<String>,
+ pub required_features: Option<Vec<String>>,
+ pub required_processors: Option<Vec<String>>,
+ pub planned_live_date: Option<String>,
+ pub miscellaneous: Option<String>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ConfiguredRouting {
pub routing_id: String,
@@ -113,6 +128,7 @@ pub enum GetMetaDataRequest {
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
+ OnboardingSurvey,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -150,4 +166,5 @@ pub enum GetMetaDataResponse {
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
+ OnboardingSurvey(Option<OnboardingSurvey>),
}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 7d9b6eb57e5..85a7e3d92df 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -348,4 +348,5 @@ pub enum DashboardMetadata {
SetupWoocomWebhook,
IsMultipleConfiguration,
IsChangePasswordRequired,
+ OnboardingSurvey,
}
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index bd4b2c3a10d..c3512c32f42 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -112,6 +112,9 @@ fn parse_set_request(data_enum: api::SetMetaDataRequest) -> UserResult<types::Me
api::SetMetaDataRequest::IsChangePasswordRequired => {
Ok(types::MetaData::IsChangePasswordRequired(true))
}
+ api::SetMetaDataRequest::OnboardingSurvey(req) => {
+ Ok(types::MetaData::OnboardingSurvey(req))
+ }
}
}
@@ -139,6 +142,7 @@ fn parse_get_request(data_enum: api::GetMetaDataRequest) -> DBEnum {
api::GetMetaDataRequest::SetupWoocomWebhook => DBEnum::SetupWoocomWebhook,
api::GetMetaDataRequest::IsMultipleConfiguration => DBEnum::IsMultipleConfiguration,
api::GetMetaDataRequest::IsChangePasswordRequired => DBEnum::IsChangePasswordRequired,
+ api::GetMetaDataRequest::OnboardingSurvey => DBEnum::OnboardingSurvey,
}
}
@@ -218,6 +222,10 @@ fn into_response(
DBEnum::IsChangePasswordRequired => Ok(api::GetMetaDataResponse::IsChangePasswordRequired(
data.is_some(),
)),
+ DBEnum::OnboardingSurvey => {
+ let resp = utils::deserialize_to_response(data)?;
+ Ok(api::GetMetaDataResponse::OnboardingSurvey(resp))
+ }
}
}
@@ -548,6 +556,17 @@ async fn insert_metadata(
)
.await
}
+ types::MetaData::OnboardingSurvey(data) => {
+ utils::insert_merchant_scoped_metadata_to_db(
+ state,
+ user.user_id,
+ user.merchant_id,
+ user.org_id,
+ metadata_key,
+ data,
+ )
+ .await
+ }
}
}
diff --git a/crates/router/src/types/domain/user/dashboard_metadata.rs b/crates/router/src/types/domain/user/dashboard_metadata.rs
index 9c00809238e..665ee1ab022 100644
--- a/crates/router/src/types/domain/user/dashboard_metadata.rs
+++ b/crates/router/src/types/domain/user/dashboard_metadata.rs
@@ -26,6 +26,7 @@ pub enum MetaData {
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
IsChangePasswordRequired(bool),
+ OnboardingSurvey(api::OnboardingSurvey),
}
impl From<&MetaData> for DBEnum {
@@ -53,6 +54,7 @@ impl From<&MetaData> for DBEnum {
MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook,
MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration,
MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired,
+ MetaData::OnboardingSurvey(_) => Self::OnboardingSurvey,
}
}
}
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index e18a6401173..3979a864944 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -214,6 +214,7 @@ pub fn separate_metadata_type_based_on_scope(
| DBEnum::DownloadWoocom
| DBEnum::ConfigureWoocom
| DBEnum::SetupWoocomWebhook
+ | DBEnum::OnboardingSurvey
| DBEnum::IsMultipleConfiguration => merchant_scoped.push(key),
DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => {
user_scoped.push(key)
diff --git a/migrations/2024-04-12-100908_add_dashboard_metadata_key_onboarding_survey/down.sql b/migrations/2024-04-12-100908_add_dashboard_metadata_key_onboarding_survey/down.sql
new file mode 100644
index 00000000000..c7c9cbeb401
--- /dev/null
+++ b/migrations/2024-04-12-100908_add_dashboard_metadata_key_onboarding_survey/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+SELECT 1;
\ No newline at end of file
diff --git a/migrations/2024-04-12-100908_add_dashboard_metadata_key_onboarding_survey/up.sql b/migrations/2024-04-12-100908_add_dashboard_metadata_key_onboarding_survey/up.sql
new file mode 100644
index 00000000000..6c69d264814
--- /dev/null
+++ b/migrations/2024-04-12-100908_add_dashboard_metadata_key_onboarding_survey/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TYPE "DashboardMetadata"
+ADD VALUE IF NOT EXISTS 'onboarding_survey';
\ No newline at end of file
|
2024-04-12T12:34:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [X] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Bug Fix: Add support for onboarding_survey enum
### 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).
-->
Until now, we've been utilising Calendly to gather comprehensive information regarding both merchants and users.
After this PR we will capture all the data from the dashboard and store it in dashboard_metadata for better insights.
## How did you test it?
1. Post OnboardingSurvey enum details
Request
```
curl --location 'http://localhost:8080/user/data?keys=OnboardingSurvey' \
--header 'Authorization: JWT token' \
--header 'Content-Type: application/json' \
--data '{
"OnboardingSurvey": {
"designation": "some designation",
"business_website": "some business website",
"about_business": "about business ",
"major_markets": [
"Europe"
],
"business_size": "business size",
"hyperswitch_req": "hyperswitch requirement",
"required_features": [
"FRM",
"Recon"
],
"required_processors": [
"Stripe"
],
"planned_live_date": "planned live date",
"miscellaneous": "some comment"
}
}'
```
2. Get OnboardingSurvey enum details request
```
curl --location 'http://localhost:8080/user/data?keys=OnboardingSurvey' \
--header 'Authorization: JWT token'
```
Response
a. If data not present for the user
`[{"OnboardingSurvey":null}]`
b. If data already present for the user
```
[
{
"OnboardingSurvey": {
"designation": "some designation",
"about_business": "about business ",
"business_website": "some business website",
"hyperswitch_req": "hyperswitch requirement",
"major_markets": [
"Europe"
],
"business_size": "business size",
"required_features": [
"FRM",
"Recon"
],
"required_processors": [
"Stripe"
],
"planned_live_date": "planned live date",
"miscellaneous": "some comment"
}
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
2d27ebb41f576b4a70fe8ec7a349444c3cfdcdcf
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4384
|
Bug: fix merchant_business_country configs of apple pay metadata
removing merchant_business_country from the connector configs as enums can not be handled in this toml file
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index ef20aa22513..ee5f3ba749f 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -246,7 +246,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -355,7 +354,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -416,7 +414,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bambora.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -477,7 +474,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -555,7 +551,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -780,7 +775,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -862,7 +856,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1278,7 +1271,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1345,7 +1337,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nmi.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1413,7 +1404,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[noon.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1493,7 +1483,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nuvei.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1801,7 +1790,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1956,7 +1944,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2114,7 +2101,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2282,7 +2268,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index be869da4775..311a029488c 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -139,7 +139,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -249,7 +248,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -324,7 +322,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -436,7 +433,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bambora.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -498,7 +494,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -666,7 +661,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -737,7 +731,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1134,7 +1127,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1386,7 +1378,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1525,7 +1516,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1598,7 +1588,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1707,7 +1696,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 78578d97927..b643f5a2fda 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -246,7 +246,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -355,7 +354,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -416,7 +414,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bambora.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -477,7 +474,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -555,7 +551,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -780,7 +775,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -862,7 +856,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1278,7 +1271,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1345,7 +1337,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nmi.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1413,7 +1404,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[noon.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1493,7 +1483,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[nuvei.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1801,7 +1790,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1956,7 +1944,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2114,7 +2101,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2282,7 +2268,6 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
-merchant_business_country="Merchant Business Country"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
|
2024-04-17T10:41:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
removing `merchant_business_country` from the connector configs as enums can not be handled in this toml file
### 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)?
-->
Can not be tested
## Checklist
<!-- Put an `x` in 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
|
ca47ea9b13ff29085f7cc4e408f2b6498b1d6e8a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4348
|
Bug: [FEATURE] Add required fields for Local Bank Transfer
### Feature Description
Add Local Bank Transfer required fields
### Possible Implementation
Add required fields for Local Bank Transfer
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 7ade016856c..ddf42d0bb6c 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -6526,14 +6526,26 @@ impl Default for super::settings::RequiredFields {
}
),
])}),
- (enums::PaymentMethodType::Multibanco,
+ (enums::PaymentMethodType::LocalBankTransfer,
ConnectorFields {
fields: HashMap::from([
(
- enums::Connector::Stripe,
+ enums::Connector::Zsl,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::new(),
+ non_mandate: HashMap::from([ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "CN".to_string(),
+ ]
+ },
+ value: None,
+ }
+ )]),
common: HashMap::new(),
}
),
|
2024-04-12T11:21:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
### Test Case
1. Create a merchant
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: "" ' \
--data-raw '{
"merchant_id": "merchant_1712920458",
"merchant_name": "NewAge Retailer",
"return_url": "https://chrome.google.com/",
"enable_payment_response_hash": false,
"payment_response_hash_key": null,
"redirect_to_merchant_with_http_post": false,
"merchant_details": {
"primary_contact_person": "joseph Test",
"primary_phone": "veniam aute officia ullamco esse",
"primary_email": "josephTest@test.com",
"secondary_contact_person": "joseph Test2",
"secondary_phone": "proident adipisicing officia nulla",
"secondary_email": "josephTest2@test.com",
"website": "https://www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"city": "San Fransico",
"country": null,
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
}
},
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": "https://webhook.site/f456e002-24c1-4e40-99ec-e0ec147fbde4",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"payout_routing_algorithm": null,
"sub_merchants_enabled": false,
"parent_merchant_id": null,
"publishable_key": "pk_snd_3b33cd9404234113804aa1accaabe22f",
"metadata": {
"city": "NY",
"unit": "245"
},
"locker_id": "m0010",
"primary_business_details": [
{
"country": "CN",
"business": "default"
}
],
"organization_id": null
}'
```
3. Create a ZSL MCA
```
curl --location 'http://localhost:8080/account/merchant_1712918904/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ""' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "zsl",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "",
"key1": ""
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "local_bank_transfer",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245",
"account_name": "transaction_processing"
},
"business_country": "CN",
"business_label": "default",
"business_sub_label": null,
"frm_configs": null,
"connector_webhook_details": {
"merchant_secret": ""
}
}'
```
5. Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ""' \
--data-raw '{
"amount": 120,
"currency": "CNY",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "111111234567890",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"country": "CN"
}
},
"browser_info": {
"language": "en"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"payment_method": "bank_transfer",
"payment_method_type": "local_bank_transfer",
"payment_method_data": {
"bank_transfer": {
"local_bank_transfer": {}
}
}
}'
```
Response
```
{
"payment_id": "pay_1inpFkvKTZOGSg31ufzK",
"merchant_id": "merchant_1712918904",
"status": "requires_confirmation",
"amount": 120,
"net_amount": 120,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_1inpFkvKTZOGSg31ufzK_secret_kIkL4HpWR1wwr7DIMVtY",
"created": "2024-04-12T10:55:04.227Z",
"currency": "CNY",
"customer_id": "111111234567890",
"customer": {
"id": "111111234567890",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_transfer",
"payment_method_data": {
"bank_transfer": {},
"billing": null
},
"payment_token": "token_TyUJSNilbY7FG1paBcJB",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": "CN",
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "local_bank_transfer",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "111111234567890",
"created_at": 1712919304,
"expires": 1712922904,
"secret": "epk_4997f299ee614df8ac99edd4d6919a50"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_NflIGu4GsRMDUMc3NTXJ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-12T11:10:04.227Z",
"fingerprint": null,
"browser_info": {
"language": "en"
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-04-12T10:55:04.265Z"
}
```
7. List Payments
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret={{client_secret}}' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{publishable_key}}' \
--data ''
```
Response
```
{
"redirect_url": "https://chrome.google.com/",
"currency": "CNY",
"payment_methods": [
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "local_bank_transfer",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"zsl"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"CN"
]
}
},
"value": "CN"
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "local_bank_transfer",
"payment_experience": null,
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": {
"eligible_connectors": [
"zsl"
]
},
"required_fields": {
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"CN"
]
}
},
"value": "CN"
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
91830f6d7965f1ba9c23925a1399fdf810a7b31a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4352
|
Bug: add filters for amount and label in payments list
Add new filters to filters payments list by:
- **amount**: filter payments on the basis of amount equal to , less than, greater than and range
- **merchant connector id**: filter payments list on the basis of merchant_connector id, which will be unique for every connector label
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index ad882880163..4a871e69ec5 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3394,6 +3394,8 @@ pub struct PaymentListFilterConstraints {
pub limit: u32,
/// The starting point within a list of objects
pub offset: Option<u32>,
+ /// The amount to filter payments list
+ pub amount_filter: Option<AmountFilter>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
pub time_range: Option<TimeRange>,
@@ -3409,6 +3411,8 @@ pub struct PaymentListFilterConstraints {
pub payment_method_type: Option<Vec<enums::PaymentMethodType>>,
/// The list of authentication types to filter payments list
pub authentication_type: Option<Vec<enums::AuthenticationType>>,
+ /// The list of merchant connector ids to filter payments list for selected label
+ pub merchant_connector_id: Option<Vec<String>>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFilters {
@@ -3440,6 +3444,12 @@ pub struct PaymentListFiltersV2 {
pub authentication_type: Vec<enums::AuthenticationType>,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AmountFilter {
+ pub start_amount: Option<i64>,
+ pub end_amount: Option<i64>,
+}
+
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
)]
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index c9caa1ea629..2c81d305bf2 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -22,7 +22,7 @@ pub static FRM_CONFIGS_EG: &str = r#"
/// Maximum limit for payments list get api
pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100;
/// Maximum limit for payments list post api with filters
-pub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 20;
+pub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 50;
/// Default limit for payments list API
pub fn default_payments_list_limit() -> u32 {
10
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 6c236729de4..ec0e0873168 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -99,6 +99,7 @@ pub trait PaymentAttemptInterface {
payment_method: Option<Vec<storage_enums::PaymentMethod>>,
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
+ merchant_connector_id: Option<Vec<String>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, errors::StorageError>;
}
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index 83b266c3470..0ab39bcbad2 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -430,12 +430,14 @@ pub struct PaymentIntentListParams {
pub offset: u32,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
+ pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<api_models::enums::Connector>>,
pub currency: Option<Vec<storage_enums::Currency>>,
pub status: Option<Vec<storage_enums::IntentStatus>>,
pub payment_method: Option<Vec<storage_enums::PaymentMethod>>,
pub payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
pub authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
+ pub merchant_connector_id: Option<Vec<String>>,
pub profile_id: Option<String>,
pub customer_id: Option<String>,
pub starting_after_id: Option<String>,
@@ -449,12 +451,14 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
offset: 0,
starting_at: value.created_gte.or(value.created_gt).or(value.created),
ending_at: value.created_lte.or(value.created_lt).or(value.created),
+ amount_filter: None,
connector: None,
currency: None,
status: None,
payment_method: None,
payment_method_type: None,
authentication_type: None,
+ merchant_connector_id: None,
profile_id: None,
customer_id: value.customer_id,
starting_after_id: value.starting_after,
@@ -470,12 +474,14 @@ impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints {
offset: 0,
starting_at: Some(value.start_time),
ending_at: value.end_time,
+ amount_filter: None,
connector: None,
currency: None,
status: None,
payment_method: None,
payment_method_type: None,
authentication_type: None,
+ merchant_connector_id: None,
profile_id: None,
customer_id: None,
starting_after_id: None,
@@ -494,12 +500,14 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF
offset: value.offset.unwrap_or_default(),
starting_at: value.time_range.map(|t| t.start_time),
ending_at: value.time_range.and_then(|t| t.end_time),
+ amount_filter: value.amount_filter,
connector: value.connector,
currency: value.currency,
status: value.status,
payment_method: value.payment_method,
payment_method_type: value.payment_method_type,
authentication_type: value.authentication_type,
+ merchant_connector_id: value.merchant_connector_id,
profile_id: value.profile_id,
customer_id: value.customer_id,
starting_after_id: None,
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 0133c52c5db..f23c2318899 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -309,6 +309,8 @@ impl PaymentAttempt {
filter_authentication_type,
))
}
+
+ #[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_attempts(
conn: &PgPooledConn,
merchant_id: &str,
@@ -317,6 +319,7 @@ impl PaymentAttempt {
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
+ merchant_connector_id: Option<Vec<String>>,
) -> StorageResult<i64> {
let mut filter = <Self as HasTable>::table()
.count()
@@ -324,19 +327,22 @@ impl PaymentAttempt {
.filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
- if let Some(connector) = connector.clone() {
+ if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
- if let Some(payment_method) = payment_method.clone() {
+ if let Some(payment_method) = payment_method {
filter = filter.filter(dsl::payment_method.eq_any(payment_method));
}
- if let Some(payment_method_type) = payment_method_type.clone() {
+ if let Some(payment_method_type) = payment_method_type {
filter = filter.filter(dsl::payment_method_type.eq_any(payment_method_type));
}
- if let Some(authentication_type) = authentication_type.clone() {
+ if let Some(authentication_type) = authentication_type {
filter = filter.filter(dsl::authentication_type.eq_any(authentication_type));
}
+ if let Some(merchant_connector_id) = merchant_connector_id {
+ filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
+ }
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f0a30fbe662..41694162046 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2573,6 +2573,7 @@ pub async fn apply_filters_on_payments(
constraints.payment_method,
constraints.payment_method_type,
constraints.authentication_type,
+ constraints.merchant_connector_id,
merchant.storage_scheme,
)
.await
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 7da40e505e8..73b519e5449 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1258,6 +1258,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method: Option<Vec<common_enums::PaymentMethod>>,
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
+ merchant_connector_id: Option<Vec<String>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
self.diesel_store
@@ -1268,6 +1269,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method,
payment_method_type,
authentication_type,
+ merchant_connector_id,
storage_scheme,
)
.await
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index c3331817784..c1d67c4ce00 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -922,14 +922,10 @@ pub async fn payments_list_by_filter(
state,
&req,
payload,
- |state, auth, req, _| {
+ |state, auth: auth::AuthenticationData, req, _| {
payments::apply_filters_on_payments(state, auth.merchant_account, req)
},
- auth::auth_type(
- &auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::PaymentRead),
- req.headers(),
- ),
+ &auth::JWTAuth(Permission::PaymentRead),
api_locking::LockAction::NotApplicable,
)
.await
@@ -948,12 +944,10 @@ pub async fn get_filters_for_payments(
state,
&req,
payload,
- |state, auth, req, _| payments::get_filters_for_payments(state, auth.merchant_account, req),
- auth::auth_type(
- &auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::PaymentRead),
- req.headers(),
- ),
+ |state, auth: auth::AuthenticationData, req, _| {
+ payments::get_filters_for_payments(state, auth.merchant_account, req)
+ },
+ &auth::JWTAuth(Permission::PaymentRead),
api_locking::LockAction::NotApplicable,
)
.await
@@ -971,12 +965,10 @@ pub async fn get_payment_filters(
state,
&req,
(),
- |state, auth, _, _| payments::get_payment_filters(state, auth.merchant_account),
- auth::auth_type(
- &auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::PaymentRead),
- req.headers(),
- ),
+ |state, auth: auth::AuthenticationData, _, _| {
+ payments::get_payment_filters(state, auth.merchant_account)
+ },
+ &auth::JWTAuth(Permission::PaymentRead),
api_locking::LockAction::NotApplicable,
)
.await
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index acec82e1721..996c8e102b7 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -42,6 +42,7 @@ impl PaymentAttemptInterface for MockDb {
_payment_method: Option<Vec<PaymentMethod>>,
_payment_method_type: Option<Vec<PaymentMethodType>>,
_authentication_type: Option<Vec<AuthenticationType>>,
+ _merchanat_connector_id: Option<Vec<String>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 138f3658aa0..6eda689c8da 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -292,6 +292,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method: Option<Vec<PaymentMethod>>,
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
+ merchant_connector_id: Option<Vec<String>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = self
@@ -314,6 +315,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
+ merchant_connector_id,
)
.await
.map_err(|er| {
@@ -1021,6 +1023,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method: Option<Vec<PaymentMethod>>,
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
+ merchant_connector_id: Option<Vec<String>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
@@ -1031,6 +1034,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
+ merchant_connector_id,
storage_scheme,
)
.await
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 8934b3ba2c6..6b4cf8b82e1 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -1,5 +1,9 @@
#[cfg(feature = "olap")]
+use api_models::payments::AmountFilter;
+#[cfg(feature = "olap")]
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
+#[cfg(feature = "olap")]
+use common_utils::errors::ReportSwitchExt;
use common_utils::{date_time, ext_traits::Encode};
#[cfg(feature = "olap")]
use data_models::payments::payment_intent::PaymentIntentFetchConstraints;
@@ -549,8 +553,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
- use common_utils::errors::ReportSwitchExt;
-
let conn = connection::pg_connection_read(self).await.switch()?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
@@ -615,9 +617,26 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
query = query.offset(params.offset.into());
- if let Some(currency) = ¶ms.currency {
- query = query.filter(pi_dsl::currency.eq_any(currency.clone()));
- }
+ query = match params.amount_filter {
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.between(start, end)),
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: None,
+ }) => query.filter(pi_dsl::amount.ge(start)),
+ Some(AmountFilter {
+ start_amount: None,
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.le(end)),
+ _ => query,
+ };
+
+ query = match ¶ms.currency {
+ Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
+ None => query,
+ };
let connectors = params
.connector
@@ -653,6 +672,13 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
None => query,
};
+ query = match ¶ms.merchant_connector_id {
+ Some(merchant_connector_id) => query.filter(
+ pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()),
+ ),
+ None => query,
+ };
+
query
}
};
@@ -690,8 +716,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
constraints: &PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
- use common_utils::errors::ReportSwitchExt;
-
let conn = connection::pg_connection_read(self).await.switch()?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
@@ -722,6 +746,22 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
None => query,
};
+ query = match params.amount_filter {
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.between(start, end)),
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: None,
+ }) => query.filter(pi_dsl::amount.ge(start)),
+ Some(AmountFilter {
+ start_amount: None,
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.le(end)),
+ _ => query,
+ };
+
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
|
2024-04-12T12:40:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR add support to filter payments list by amount and merchant connector 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
closes #4352
## How did you test it?
curl to test amount filter
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
"amount_filter": {
"start_amount": 16934,
"end_amount": 17000
}
}
}'
```
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
"amount_filter": {
"start_amount": 16934,
}
}'
```
To apply merchant_connector_id filter:
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_connector_id": ["mca_test1","mac_test"]
}'
```
Both filters can also be simultaneously by passing them in json body. And the response after applying above filters will be filters payment list response, something like:
```
{
"count": 1,
"total_count": 1,
"data": [
{
"payment_id": "test_9jWD1XIJKZuonpCk4Cdn",
"merchant_id": "merchant_1712924675",
"status": "failed",
"amount": 17000,
"net_amount": 0,
"amount_capturable": 17000,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_9jWD1XIJKZuonpCk4Cdn_secret_l4KaD6efemXZ9oDLGIVI",
"created": "2024-04-10T02:25:35.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_9jWD1XIJKZuonpCk4Cdn_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_0xtUwT8bnGnMR2hYjEJB",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null
}
]
}
```
## Checklist
<!-- Put an `x` in 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
|
5a0a8cee76378b826580fb44f7d6d6a9b254677e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4340
|
Bug: [FIX] parsing leap seconds
Currently we are facing errors while parsing leap seconds in ISO8601 format, [this commit](https://github.com/time-rs/time/commit/9c15ee34668fc99c918656fb2895b6d0bfdf7d75) fixes it in `time` crate
|
diff --git a/Cargo.lock b/Cargo.lock
index f17cd059480..92a998dbf57 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6978,9 +6978,9 @@ dependencies = [
[[package]]
name = "time"
-version = "0.3.34"
+version = "0.3.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749"
+checksum = "ef89ece63debf11bc32d1ed8d078ac870cbeb44da02afb02a9ff135ae7ca0582"
dependencies = [
"deranged",
"itoa",
@@ -7001,9 +7001,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
[[package]]
name = "time-macros"
-version = "0.2.17"
+version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774"
+checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf"
dependencies = [
"num-conv",
"time-core",
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index 2b1cc798a7e..c3e35519dce 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -37,5 +37,5 @@ serde_json = "1.0.115"
sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] }
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index cdcee9c506e..0bd0b01a278 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -30,7 +30,7 @@ reqwest = { version = "0.11.27", optional = true }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
url = { version = "2.5.0", features = ["serde"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
frunk = "0.4.2"
diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml
index ab4152893af..ac8a417fb99 100644
--- a/crates/cards/Cargo.toml
+++ b/crates/cards/Cargo.toml
@@ -14,7 +14,7 @@ error-stack = "0.4.1"
luhn = "1.0.1"
serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
-time = "0.3.34"
+time = "0.3.35"
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils" }
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index 285d423958d..6f08649fbda 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -36,7 +36,7 @@ serde_urlencoded = "0.7.1"
signal-hook = { version = "0.3.17", optional = true }
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional = true }
semver = { version = "1.0.22", features = ["serde"] }
uuid = { version = "1.8.0", features = ["v7"] }
diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs
index e4608c4f371..79e0c5b85e7 100644
--- a/crates/common_utils/src/custom_serde.rs
+++ b/crates/common_utils/src/custom_serde.rs
@@ -265,3 +265,22 @@ pub mod iso8601custom {
})
}
}
+
+#[cfg(test)]
+mod tests {
+ use serde::{Deserialize, Serialize};
+ use serde_json::json;
+
+ #[test]
+ fn test_leap_second_parse() {
+ #[derive(Serialize, Deserialize)]
+ struct Try {
+ #[serde(with = "crate::custom_serde::iso8601")]
+ f: time::PrimitiveDateTime,
+ }
+ let leap_second_date_time = json!({"f": "2023-12-31T23:59:60.000Z"});
+ let deser = serde_json::from_value::<Try>(leap_second_date_time);
+
+ assert!(deser.is_ok())
+ }
+}
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index b1a708f7a08..7b8b7bb9490 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -23,15 +23,15 @@ pub mod validation;
/// Date-time utilities.
pub mod date_time {
+ #[cfg(feature = "async_ext")]
+ use std::time::Instant;
use std::{marker::PhantomData, num::NonZeroU8};
use masking::{Deserialize, Serialize};
- #[cfg(feature = "async_ext")]
- use time::Instant;
use time::{
format_description::{
well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision},
- FormatItem,
+ BorrowedFormatItem,
},
OffsetDateTime, PrimitiveDateTime,
};
@@ -68,7 +68,7 @@ pub mod date_time {
) -> (T, f64) {
let start = Instant::now();
let result = block().await;
- (result, start.elapsed().as_seconds_f64() * 1000f64)
+ (result, start.elapsed().as_secs_f64() * 1000f64)
}
/// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132
@@ -76,7 +76,7 @@ pub mod date_time {
date: PrimitiveDateTime,
format: DateFormat,
) -> Result<String, time::error::Format> {
- let format = <&[FormatItem<'_>]>::from(format);
+ let format = <&[BorrowedFormatItem<'_>]>::from(format);
date.format(&format)
}
@@ -90,7 +90,7 @@ pub mod date_time {
now().assume_utc().format(&Iso8601::<ISO_CONFIG>)
}
- impl From<DateFormat> for &[FormatItem<'_>] {
+ impl From<DateFormat> for &[BorrowedFormatItem<'_>] {
fn from(format: DateFormat) -> Self {
match format {
DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
diff --git a/crates/data_models/Cargo.toml b/crates/data_models/Cargo.toml
index 6da89dc2325..54130ca002a 100644
--- a/crates/data_models/Cargo.toml
+++ b/crates/data_models/Cargo.toml
@@ -26,4 +26,4 @@ error-stack = "0.4.1"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
thiserror = "1.0.58"
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index 85533d0cf33..577233cdf1a 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -21,7 +21,7 @@ serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
# First party crates
common_enums = { version = "0.1.0", path = "../common_enums" }
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 002e22ec4d8..36999fa0667 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -87,7 +87,7 @@ sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-to
strum = { version = "0.26", features = ["derive"] }
tera = "1.19.1"
thiserror = "1.0.58"
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
unicode-segmentation = "1.11.0"
url = { version = "2.5.0", features = ["serde"] }
@@ -134,7 +134,7 @@ awc = { version = "3.4.0", features = ["rustls"] }
derive_deref = "1.1.1"
rand = "0.8.5"
serial_test = "3.0.0"
-time = { version = "0.3.34", features = ["macros"] }
+time = { version = "0.3.35", features = ["macros"] }
tokio = "1.37.0"
wiremock = "0.6.0"
diff --git a/crates/router/tests/connectors/ebanx.rs b/crates/router/tests/connectors/ebanx.rs
index 5ef703469ea..0c675be2242 100644
--- a/crates/router/tests/connectors/ebanx.rs
+++ b/crates/router/tests/connectors/ebanx.rs
@@ -306,7 +306,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 72f0f0b39ac..3b95d5f22fd 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -20,7 +20,7 @@ serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
serde_path_to_error = "0.1.16"
strum = { version = "0.26.2", features = ["derive"] }
-time = { version = "0.3.34", default-features = false, features = ["formatting"] }
+time = { version = "0.3.35", default-features = false, features = ["formatting"] }
tokio = { version = "1.37.0" }
tracing = { version = "0.1.40" }
tracing-actix-web = { version = "0.7.10", features = ["opentelemetry_0_19", "uuid_v7"], optional = true }
diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml
index f713b8f2f2b..b98f212d674 100644
--- a/crates/scheduler/Cargo.toml
+++ b/crates/scheduler/Cargo.toml
@@ -23,7 +23,7 @@ serde = "1.0.197"
serde_json = "1.0.115"
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
-time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
uuid = { version = "1.8.0", features = ["v4"] }
diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml
index 714e34f0e95..3b0dfe2b91d 100644
--- a/crates/test_utils/Cargo.toml
+++ b/crates/test_utils/Cargo.toml
@@ -24,7 +24,7 @@ serde_json = "1.0.115"
serde_urlencoded = "0.7.1"
serial_test = "3.0.0"
thirtyfour = "0.31.0"
-time = { version = "0.3.34", features = ["macros"] }
+time = { version = "0.3.35", features = ["macros"] }
tokio = "1.37.0"
toml = "0.8.12"
|
2024-04-10T10:32:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Dependency updates
## Description
<!-- Describe your changes in detail -->
Update the time crate to `0.3.35` version
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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 version of the time crate fixes a critical bug where `IS8601` breaks while parsing leap seconds
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cannot be tested in sandbox
- Ran `cargo test -p common_utils test_leap_second_parse` locally and verify the testcase is running
## Checklist
<!-- Put an `x` in 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
|
ce1e165cecade481ce6002795049d6a9ffec96e2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4336
|
Bug: add `ApiKeyAuth` support for `upsert_connector_agnostic_mandate_config`
Add support for api-key auth for pg_agnotic config api enpoint. As it is required by merchant to enable the config until the dashboard changes are done.
|
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 28d65f66a82..5d8330a05b4 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -591,14 +591,11 @@ pub async fn upsert_connector_agnostic_mandate_config(
mandate_config,
))
},
- #[cfg(not(feature = "release"))]
auth::auth_type(
&auth::ApiKeyAuth,
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
- #[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
api_locking::LockAction::NotApplicable,
))
.await
|
2024-04-10T09:39:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add support for api-key auth for `pg_agnotic` config api enpoint.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/routing/business_profile/{{business_profile_id}}/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api-key' \
--data '{
"enabled": true
}'
```

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
a2958c33b5c4ed627c97e97e791ca2cfbfcecd5e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4372
|
Bug: Add vector service to accept events from SDK
Need to add a [vector](https://vector.dev/) service to accept events from SDK & insert them to kafka/clickhouse.
This URL can be configured as an env in SDK container/deployment and it can forward the data to the kafka containers in the stack.
|
diff --git a/config/dashboard.toml b/config/dashboard.toml
index c00b167315a..142cc966500 100644
--- a/config/dashboard.toml
+++ b/config/dashboard.toml
@@ -25,8 +25,8 @@ test_processors=true
feedback=false
mixpanel=false
generate_report=false
-user_journey_analytics=false
-authentication_analytics=false
+user_journey_analytics=true
+authentication_analytics=true
surcharge=false
dispute_evidence_upload=false
paypal_automatic_flow=false
diff --git a/config/vector.yaml b/config/vector.yaml
index d8f5da34666..1511e09a05c 100644
--- a/config/vector.yaml
+++ b/config/vector.yaml
@@ -29,6 +29,11 @@ sources:
node_metrics:
type: host_metrics
+ sdk_source:
+ type: http_server
+ address: 0.0.0.0:3103
+ encoding: json
+
transforms:
plus_1_events:
type: filter
@@ -56,6 +61,14 @@ transforms:
source: |-
.timestamp = from_unix_timestamp!(.created_at, unit: "seconds")
+ sdk_transformed:
+ type: throttle
+ inputs:
+ - sdk_source
+ key_field: "{{ .payment_id }}{{ .merchant_id }}"
+ threshold: 1000
+ window_secs: 60
+
sinks:
opensearch_events:
type: elasticsearch
@@ -132,3 +145,16 @@ sinks:
inputs:
- vector_metrics
- node_metrics
+
+ sdk_sink:
+ type: kafka
+ encoding:
+ codec: json
+ except_fields:
+ - "path"
+ - "source_type"
+ inputs:
+ - "sdk_transformed"
+ bootstrap_servers: kafka0:29092
+ topic: hyper-sdk-logs
+ key_field: ".merchant_id"
diff --git a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql
new file mode 100644
index 00000000000..54480fa99b8
--- /dev/null
+++ b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql
@@ -0,0 +1,250 @@
+CREATE TABLE sdk_events_queue (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `remote_ip` Nullable(String),
+ `log_type` LowCardinality(Nullable(String)),
+ `event_name` LowCardinality(Nullable(String)),
+ `first_event` LowCardinality(Nullable(String)),
+ `latency` Nullable(UInt32),
+ `timestamp` String,
+ `browser_name` LowCardinality(Nullable(String)),
+ `browser_version` Nullable(String),
+ `platform` LowCardinality(Nullable(String)),
+ `source` LowCardinality(Nullable(String)),
+ `category` LowCardinality(Nullable(String)),
+ `version` LowCardinality(Nullable(String)),
+ `value` Nullable(String),
+ `component` LowCardinality(Nullable(String)),
+ `payment_method` LowCardinality(Nullable(String)),
+ `payment_experience` LowCardinality(Nullable(String))
+) ENGINE = Kafka SETTINGS
+ kafka_broker_list = 'kafka0:29092',
+ kafka_topic_list = 'hyper-sdk-logs',
+ kafka_group_name = 'hyper-ckh',
+ kafka_format = 'JSONEachRow',
+ kafka_handle_error_mode = 'stream';
+
+CREATE TABLE sdk_events (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `remote_ip` Nullable(String),
+ `log_type` LowCardinality(Nullable(String)),
+ `event_name` LowCardinality(Nullable(String)),
+ `first_event` Bool DEFAULT 1,
+ `browser_name` LowCardinality(Nullable(String)),
+ `browser_version` Nullable(String),
+ `platform` LowCardinality(Nullable(String)),
+ `source` LowCardinality(Nullable(String)),
+ `category` LowCardinality(Nullable(String)),
+ `version` LowCardinality(Nullable(String)),
+ `component` LowCardinality(Nullable(String)),
+ `payment_method` LowCardinality(Nullable(String)),
+ `payment_experience` LowCardinality(Nullable(String)) DEFAULT '',
+ `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `latency` Nullable(UInt32) DEFAULT 0,
+ `value` Nullable(String),
+ `created_at_precise` DateTime64(3),
+ INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,
+ INDEX eventIndex event_name TYPE bloom_filter GRANULARITY 1,
+ INDEX platformIndex platform TYPE bloom_filter GRANULARITY 1,
+ INDEX logTypeIndex log_type TYPE bloom_filter GRANULARITY 1,
+ INDEX categoryIndex category TYPE bloom_filter GRANULARITY 1,
+ INDEX sourceIndex source TYPE bloom_filter GRANULARITY 1,
+ INDEX componentIndex component TYPE bloom_filter GRANULARITY 1,
+ INDEX firstEventIndex first_event TYPE bloom_filter GRANULARITY 1
+) ENGINE = MergeTree
+PARTITION BY
+ toStartOfDay(created_at)
+ORDER BY
+ (created_at, merchant_id)
+TTL
+ toDateTime(created_at) + toIntervalMonth(6)
+SETTINGS
+ index_granularity = 8192
+;
+
+CREATE MATERIALIZED VIEW sdk_events_mv TO sdk_events (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `remote_ip` Nullable(String),
+ `log_type` LowCardinality(Nullable(String)),
+ `event_name` LowCardinality(Nullable(String)),
+ `first_event` Bool,
+ `latency` Nullable(UInt32),
+ `browser_name` LowCardinality(Nullable(String)),
+ `browser_version` Nullable(String),
+ `platform` LowCardinality(Nullable(String)),
+ `source` LowCardinality(Nullable(String)),
+ `category` LowCardinality(Nullable(String)),
+ `version` LowCardinality(Nullable(String)),
+ `value` Nullable(String),
+ `component` LowCardinality(Nullable(String)),
+ `payment_method` LowCardinality(Nullable(String)),
+ `payment_experience` LowCardinality(Nullable(String)),
+ `created_at` DateTime64(3),
+ `created_at_precise` DateTime64(3)
+) AS
+SELECT
+ payment_id,
+ merchant_id,
+ remote_ip,
+ log_type,
+ event_name,
+ multiIf(first_event = 'true', 1, 0) AS first_event,
+ latency,
+ browser_name,
+ browser_version,
+ platform,
+ source,
+ category,
+ version,
+ value,
+ component,
+ payment_method,
+ payment_experience,
+ toDateTime64(timestamp, 3) AS created_at,
+ toDateTime64(timestamp, 3) AS created_at_precise
+FROM
+ sdk_events_queue
+WHERE length(_error) = 0;
+
+CREATE TABLE sdk_events_audit (
+ `payment_id` String,
+ `merchant_id` String,
+ `remote_ip` Nullable(String),
+ `log_type` LowCardinality(Nullable(String)),
+ `event_name` LowCardinality(Nullable(String)),
+ `first_event` Bool DEFAULT 1,
+ `browser_name` LowCardinality(Nullable(String)),
+ `browser_version` Nullable(String),
+ `platform` LowCardinality(Nullable(String)),
+ `source` LowCardinality(Nullable(String)),
+ `category` LowCardinality(Nullable(String)),
+ `version` LowCardinality(Nullable(String)),
+ `value` Nullable(String),
+ `component` LowCardinality(Nullable(String)),
+ `payment_method` LowCardinality(Nullable(String)),
+ `payment_experience` LowCardinality(Nullable(String)) DEFAULT '',
+ `created_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `latency` Nullable(UInt32) DEFAULT 0
+) ENGINE = MergeTree PARTITION BY merchant_id
+ORDER BY
+ (merchant_id, payment_id)
+ TTL inserted_at + toIntervalMonth(18)
+SETTINGS index_granularity = 8192;
+
+CREATE MATERIALIZED VIEW sdk_events_parse_errors (
+ `topic` String,
+ `partition` Int64,
+ `offset` Int64,
+ `raw` String,
+ `error` String
+) ENGINE = MergeTree
+ORDER BY
+ (topic, partition, offset) SETTINGS index_granularity = 8192 AS
+SELECT
+ _topic AS topic,
+ _partition AS partition,
+ _offset AS offset,
+ _raw_message AS raw,
+ _error AS error
+FROM
+ sdk_events_queue
+WHERE
+ length(_error) > 0;
+
+CREATE MATERIALIZED VIEW sdk_events_audit_mv TO sdk_events_audit (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `remote_ip` Nullable(String),
+ `log_type` LowCardinality(Nullable(String)),
+ `event_name` LowCardinality(Nullable(String)),
+ `first_event` Bool,
+ `latency` Nullable(UInt32),
+ `browser_name` LowCardinality(Nullable(String)),
+ `browser_version` Nullable(String),
+ `platform` LowCardinality(Nullable(String)),
+ `source` LowCardinality(Nullable(String)),
+ `category` LowCardinality(Nullable(String)),
+ `version` LowCardinality(Nullable(String)),
+ `value` Nullable(String),
+ `component` LowCardinality(Nullable(String)),
+ `payment_method` LowCardinality(Nullable(String)),
+ `payment_experience` LowCardinality(Nullable(String)),
+ `created_at` DateTime64(3),
+ `created_at_precise` DateTime64(3),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4)
+) AS
+SELECT
+ payment_id,
+ merchant_id,
+ remote_ip,
+ log_type,
+ event_name,
+ multiIf(first_event = 'true', 1, 0) AS first_event,
+ latency,
+ browser_name,
+ browser_version,
+ platform,
+ source,
+ category,
+ version,
+ value,
+ component,
+ payment_method,
+ payment_experience,
+ toDateTime64(timestamp, 3) AS created_at,
+ toDateTime64(timestamp, 3) AS created_at_precise,
+ now() AS inserted_at
+FROM
+ sdk_events_queue
+WHERE
+ (length(_error) = 0)
+ AND (payment_id IS NOT NULL);
+
+CREATE TABLE active_payments (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `created_at` DateTime64,
+ `flow_type` LowCardinality(Nullable(String)),
+ INDEX merchantIndex merchant_id TYPE bloom_filter GRANULARITY 1
+) ENGINE = MergeTree
+PARTITION BY toStartOfSecond(created_at)
+ORDER BY
+ merchant_id
+TTL
+ toDateTime(created_at) + INTERVAL 60 SECOND
+SETTINGS
+ index_granularity = 8192;
+
+CREATE MATERIALIZED VIEW sdk_active_payments_mv TO active_payments (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `created_at` DateTime64,
+ `flow_type` LowCardinality(Nullable(String))
+) AS
+SELECT
+ payment_id,
+ merchant_id,
+ toDateTime64(timestamp, 3) AS created_at,
+ 'sdk' AS flow_type
+FROM
+ sdk_events_queue
+WHERE length(_error) = 0;
+
+CREATE MATERIALIZED VIEW api_active_payments_mv TO active_payments (
+ `payment_id` Nullable(String),
+ `merchant_id` String,
+ `created_at` DateTime64,
+ `flow_type` LowCardinality(Nullable(String))
+) AS
+SELECT
+ payment_id,
+ merchant_id,
+ created_at_timestamp AS created_at,
+ flow_type
+FROM
+ api_events_queue
+WHERE length(_error) = 0;
\ No newline at end of file
diff --git a/crates/analytics/src/active_payments.rs b/crates/analytics/src/active_payments.rs
new file mode 100644
index 00000000000..518e15b7c0d
--- /dev/null
+++ b/crates/analytics/src/active_payments.rs
@@ -0,0 +1,6 @@
+pub mod accumulator;
+mod core;
+pub mod metrics;
+pub use accumulator::{ActivePaymentsMetricAccumulator, ActivePaymentsMetricsAccumulator};
+
+pub use self::core::get_metrics;
diff --git a/crates/analytics/src/active_payments/accumulator.rs b/crates/analytics/src/active_payments/accumulator.rs
new file mode 100644
index 00000000000..2576a8a308b
--- /dev/null
+++ b/crates/analytics/src/active_payments/accumulator.rs
@@ -0,0 +1,47 @@
+use api_models::analytics::active_payments::ActivePaymentsMetricsBucketValue;
+
+use super::metrics::ActivePaymentsMetricRow;
+
+#[derive(Debug, Default)]
+pub struct ActivePaymentsMetricsAccumulator {
+ pub active_payments: CountAccumulator,
+}
+
+#[derive(Debug, Default)]
+#[repr(transparent)]
+pub struct CountAccumulator {
+ pub count: Option<i64>,
+}
+
+pub trait ActivePaymentsMetricAccumulator {
+ type MetricOutput;
+
+ fn add_metrics_bucket(&mut self, metrics: &ActivePaymentsMetricRow);
+
+ fn collect(self) -> Self::MetricOutput;
+}
+
+impl ActivePaymentsMetricAccumulator for CountAccumulator {
+ type MetricOutput = Option<u64>;
+ #[inline]
+ fn add_metrics_bucket(&mut self, metrics: &ActivePaymentsMetricRow) {
+ self.count = match (self.count, metrics.count) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ }
+ }
+ #[inline]
+ fn collect(self) -> Self::MetricOutput {
+ self.count.and_then(|i| u64::try_from(i).ok())
+ }
+}
+
+impl ActivePaymentsMetricsAccumulator {
+ #[allow(dead_code)]
+ pub fn collect(self) -> ActivePaymentsMetricsBucketValue {
+ ActivePaymentsMetricsBucketValue {
+ active_payments: self.active_payments.collect(),
+ }
+ }
+}
diff --git a/crates/analytics/src/active_payments/core.rs b/crates/analytics/src/active_payments/core.rs
new file mode 100644
index 00000000000..0024581bf85
--- /dev/null
+++ b/crates/analytics/src/active_payments/core.rs
@@ -0,0 +1,106 @@
+use std::collections::HashMap;
+
+use api_models::analytics::{
+ active_payments::{
+ ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier, MetricsBucketResponse,
+ },
+ AnalyticsMetadata, GetActivePaymentsMetricRequest, MetricsResponse,
+};
+use error_stack::ResultExt;
+use router_env::{instrument, logger, tracing};
+
+use super::ActivePaymentsMetricsAccumulator;
+use crate::{
+ active_payments::ActivePaymentsMetricAccumulator,
+ errors::{AnalyticsError, AnalyticsResult},
+ AnalyticsProvider,
+};
+
+#[instrument(skip_all)]
+pub async fn get_metrics(
+ pool: &AnalyticsProvider,
+ publishable_key: Option<&String>,
+ merchant_id: Option<&String>,
+ req: GetActivePaymentsMetricRequest,
+) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
+ let mut metrics_accumulator: HashMap<
+ ActivePaymentsMetricsBucketIdentifier,
+ ActivePaymentsMetricsAccumulator,
+ > = HashMap::new();
+
+ if let Some(publishable_key) = publishable_key {
+ if let Some(merchant_id) = merchant_id {
+ let mut set = tokio::task::JoinSet::new();
+ for metric_type in req.metrics.iter().cloned() {
+ let publishable_key_scoped = publishable_key.to_owned();
+ let merchant_id_scoped = merchant_id.to_owned();
+ let pool = pool.clone();
+ set.spawn(async move {
+ let data = pool
+ .get_active_payments_metrics(
+ &metric_type,
+ &merchant_id_scoped,
+ &publishable_key_scoped,
+ )
+ .await
+ .change_context(AnalyticsError::UnknownError);
+ (metric_type, data)
+ });
+ }
+
+ while let Some((metric, data)) = set
+ .join_next()
+ .await
+ .transpose()
+ .change_context(AnalyticsError::UnknownError)?
+ {
+ logger::info!("Logging metric: {metric} Result: {:?}", data);
+ for (id, value) in data? {
+ let metrics_builder = metrics_accumulator.entry(id).or_default();
+ match metric {
+ ActivePaymentsMetrics::ActivePayments => {
+ metrics_builder.active_payments.add_metrics_bucket(&value)
+ }
+ }
+ }
+
+ logger::debug!(
+ "Analytics Accumulated Results: metric: {}, results: {:#?}",
+ metric,
+ metrics_accumulator
+ );
+ }
+
+ let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
+ .into_iter()
+ .map(|(id, val)| MetricsBucketResponse {
+ values: val.collect(),
+ dimensions: id,
+ })
+ .collect();
+
+ Ok(MetricsResponse {
+ query_data,
+ meta_data: [AnalyticsMetadata {
+ current_time_range: req.time_range,
+ }],
+ })
+ } else {
+ logger::error!("Merchant ID not present");
+ Ok(MetricsResponse {
+ query_data: vec![],
+ meta_data: [AnalyticsMetadata {
+ current_time_range: req.time_range,
+ }],
+ })
+ }
+ } else {
+ logger::error!("Publishable key not present for merchant ID");
+ Ok(MetricsResponse {
+ query_data: vec![],
+ meta_data: [AnalyticsMetadata {
+ current_time_range: req.time_range,
+ }],
+ })
+ }
+}
diff --git a/crates/analytics/src/active_payments/metrics.rs b/crates/analytics/src/active_payments/metrics.rs
new file mode 100644
index 00000000000..43a0b229c8b
--- /dev/null
+++ b/crates/analytics/src/active_payments/metrics.rs
@@ -0,0 +1,70 @@
+use api_models::analytics::{
+ active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier},
+ Granularity,
+};
+use time::PrimitiveDateTime;
+
+use crate::{
+ query::{Aggregate, GroupByClause, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult},
+};
+
+mod active_payments;
+
+use active_payments::ActivePayments;
+
+#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
+pub struct ActivePaymentsMetricRow {
+ pub count: Option<i64>,
+}
+
+pub trait ActivePaymentsMetricAnalytics: LoadRow<ActivePaymentsMetricRow> {}
+
+#[async_trait::async_trait]
+pub trait ActivePaymentsMetric<T>
+where
+ T: AnalyticsDataSource + ActivePaymentsMetricAnalytics,
+{
+ async fn load_metrics(
+ &self,
+ merchant_id: &str,
+ publishable_key: &str,
+ pool: &T,
+ ) -> MetricsResult<
+ Vec<(
+ ActivePaymentsMetricsBucketIdentifier,
+ ActivePaymentsMetricRow,
+ )>,
+ >;
+}
+
+#[async_trait::async_trait]
+impl<T> ActivePaymentsMetric<T> for ActivePaymentsMetrics
+where
+ T: AnalyticsDataSource + ActivePaymentsMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ merchant_id: &str,
+ publishable_key: &str,
+ pool: &T,
+ ) -> MetricsResult<
+ Vec<(
+ ActivePaymentsMetricsBucketIdentifier,
+ ActivePaymentsMetricRow,
+ )>,
+ > {
+ match self {
+ Self::ActivePayments => {
+ ActivePayments
+ .load_metrics(publishable_key, merchant_id, pool)
+ .await
+ }
+ }
+ }
+}
diff --git a/crates/analytics/src/active_payments/metrics/active_payments.rs b/crates/analytics/src/active_payments/metrics/active_payments.rs
new file mode 100644
index 00000000000..97b3e69d1ca
--- /dev/null
+++ b/crates/analytics/src/active_payments/metrics/active_payments.rs
@@ -0,0 +1,70 @@
+use api_models::analytics::{active_payments::ActivePaymentsMetricsBucketIdentifier, Granularity};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::ActivePaymentsMetricRow;
+use crate::{
+ query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(super) struct ActivePayments;
+
+#[async_trait::async_trait]
+impl<T> super::ActivePaymentsMetric<T> for ActivePayments
+where
+ T: AnalyticsDataSource + super::ActivePaymentsMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ merchant_id: &str,
+ publishable_key: &str,
+ pool: &T,
+ ) -> MetricsResult<
+ Vec<(
+ ActivePaymentsMetricsBucketIdentifier,
+ ActivePaymentsMetricRow,
+ )>,
+ > {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::ActivePaymentsAnalytics);
+
+ query_builder
+ .add_select_column(Aggregate::DistinctCount {
+ field: "payment_id",
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_custom_filter_clause(
+ "merchant_id",
+ format!("'{}','{}'", merchant_id, publishable_key),
+ FilterTypes::In,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<ActivePaymentsMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| Ok((ActivePaymentsMetricsBucketIdentifier::new(None), i)))
+ .collect::<error_stack::Result<
+ Vec<(
+ ActivePaymentsMetricsBucketIdentifier,
+ ActivePaymentsMetricRow,
+ )>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
index dd65458b1e3..01110858804 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
@@ -33,7 +33,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
query_builder
.add_select_column(Aggregate::Count {
diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
index 7559abe8e2a..6f0580bb0b5 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
@@ -33,7 +33,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
query_builder
.add_select_column(Aggregate::Count {
diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
index 51a3b8ed88e..49fef8941f7 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
@@ -33,7 +33,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
query_builder
.add_select_column(Aggregate::Count {
diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
index b5760c9dfa2..7ae9d773675 100644
--- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
+++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
@@ -33,7 +33,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
query_builder
.add_select_column(Aggregate::Count {
diff --git a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs
index be9d7ab0dcf..b08d48b550a 100644
--- a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs
+++ b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs
@@ -33,7 +33,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
query_builder
.add_select_column(Aggregate::Count {
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 47294c108f3..ab47397b8af 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -7,6 +7,7 @@ use router_env::logger;
use time::PrimitiveDateTime;
use super::{
+ active_payments::metrics::ActivePaymentsMetricRow,
auth_events::metrics::AuthEventMetricRow,
health_check::HealthCheck,
payments::{
@@ -133,10 +134,12 @@ impl AnalyticsDataSource for ClickhouseClient {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
}
AnalyticsCollection::SdkEvents
+ | AnalyticsCollection::SdkEventsAnalytics
| AnalyticsCollection::ApiEvents
| AnalyticsCollection::ConnectorEvents
| AnalyticsCollection::ApiEventsAnalytics
- | AnalyticsCollection::OutgoingWebhookEvent => TableEngine::BasicTree,
+ | AnalyticsCollection::OutgoingWebhookEvent
+ | AnalyticsCollection::ActivePaymentsAnalytics => TableEngine::BasicTree,
}
}
}
@@ -159,6 +162,7 @@ impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {}
impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {}
+impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {}
impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {}
impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {}
impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {}
@@ -353,6 +357,16 @@ impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value {
}
}
+impl TryInto<ActivePaymentsMetricRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<ActivePaymentsMetricRow, Self::Error> {
+ serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
+ "Failed to parse ActivePaymentsMetricRow in clickhouse results",
+ ))
+ }
+}
+
impl ToSql<ClickhouseClient> for PrimitiveDateTime {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
let format =
@@ -373,12 +387,14 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection {
Self::Payment => Ok("payment_attempts".to_string()),
Self::Refund => Ok("refunds".to_string()),
Self::SdkEvents => Ok("sdk_events_audit".to_string()),
+ Self::SdkEventsAnalytics => Ok("sdk_events".to_string()),
Self::ApiEvents => Ok("api_events_audit".to_string()),
Self::ApiEventsAnalytics => Ok("api_events".to_string()),
Self::PaymentIntent => Ok("payment_intents".to_string()),
Self::ConnectorEvents => Ok("connector_events_audit".to_string()),
Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()),
Self::Dispute => Ok("dispute".to_string()),
+ Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()),
}
}
}
@@ -451,6 +467,15 @@ where
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
)
}
+ Self::DistinctCount { field, alias } => {
+ format!(
+ "count(distinct {}){}",
+ field
+ .to_sql(table_engine)
+ .attach_printable("Failed to percentile aggregate")?,
+ alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
+ )
+ }
})
}
}
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 5c269a4bb18..d3db03a6977 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -7,6 +7,7 @@ pub mod payments;
mod query;
pub mod refunds;
+pub mod active_payments;
pub mod api_event;
pub mod auth_events;
pub mod connector_events;
@@ -32,6 +33,7 @@ pub mod utils;
use std::sync::Arc;
use api_models::analytics::{
+ active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier},
api_event::{
ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier,
},
@@ -56,6 +58,7 @@ use storage_impl::config::Database;
use strum::Display;
use self::{
+ active_payments::metrics::{ActivePaymentsMetric, ActivePaymentsMetricRow},
auth_events::metrics::{AuthEventMetric, AuthEventMetricRow},
payments::{
distribution::{PaymentDistribution, PaymentDistributionRow},
@@ -514,7 +517,7 @@ impl AnalyticsProvider {
&self,
metric: &SdkEventMetrics,
dimensions: &[SdkEventDimensions],
- pub_key: &str,
+ publishable_key: &str,
filters: &SdkEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -523,14 +526,21 @@ impl AnalyticsProvider {
Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)),
Self::Clickhouse(pool) => {
metric
- .load_metrics(dimensions, pub_key, filters, granularity, time_range, pool)
+ .load_metrics(
+ dimensions,
+ publishable_key,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
.await
}
Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => {
metric
.load_metrics(
dimensions,
- pub_key,
+ publishable_key,
filters,
granularity,
// Since SDK events are ckh only use ckh here
@@ -542,6 +552,32 @@ impl AnalyticsProvider {
}
}
+ pub async fn get_active_payments_metrics(
+ &self,
+ metric: &ActivePaymentsMetrics,
+ merchant_id: &str,
+ publishable_key: &str,
+ ) -> types::MetricsResult<
+ Vec<(
+ ActivePaymentsMetricsBucketIdentifier,
+ ActivePaymentsMetricRow,
+ )>,
+ > {
+ match self {
+ Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)),
+ Self::Clickhouse(pool) => {
+ metric
+ .load_metrics(merchant_id, publishable_key, pool)
+ .await
+ }
+ Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => {
+ metric
+ .load_metrics(merchant_id, publishable_key, ckh_pool)
+ .await
+ }
+ }
+ }
+
pub async fn get_auth_event_metrics(
&self,
metric: &AuthEventMetrics,
@@ -723,6 +759,7 @@ pub enum AnalyticsFlow {
GetRefundsMetrics,
GetSdkMetrics,
GetAuthMetrics,
+ GetActivePaymentsMetrics,
GetPaymentFilters,
GetRefundFilters,
GetSdkEventFilters,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index 1ab79f07e43..2fda8fc57cd 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -253,6 +253,10 @@ pub enum Aggregate<R> {
alias: Option<&'static str>,
percentile: Option<&'static u8>,
},
+ DistinctCount {
+ field: R,
+ alias: Option<&'static str>,
+ },
}
// Window functions in query
diff --git a/crates/analytics/src/sdk_events/filters.rs b/crates/analytics/src/sdk_events/filters.rs
index 9963f51ef94..367db62b183 100644
--- a/crates/analytics/src/sdk_events/filters.rs
+++ b/crates/analytics/src/sdk_events/filters.rs
@@ -24,7 +24,8 @@ where
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
query_builder.add_select_column(dimension).switch()?;
time_range
diff --git a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs
index a81a55a2af3..88c96d33efb 100644
--- a/crates/analytics/src/sdk_events/metrics/average_payment_time.rs
+++ b/crates/analytics/src/sdk_events/metrics/average_payment_time.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/load_time.rs b/crates/analytics/src/sdk_events/metrics/load_time.rs
index 07168069b54..4624f304295 100644
--- a/crates/analytics/src/sdk_events/metrics/load_time.rs
+++ b/crates/analytics/src/sdk_events/metrics/load_time.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs
index b2a78188c4f..7cbe93056a9 100644
--- a/crates/analytics/src/sdk_events/metrics/payment_attempts.rs
+++ b/crates/analytics/src/sdk_events/metrics/payment_attempts.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs
index a3c94baeda2..aff78808d1d 100644
--- a/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs
+++ b/crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs
index 11aeac5e6ff..284519441a7 100644
--- a/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs
+++ b/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs
index 7570f1292e5..e7dc6504036 100644
--- a/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs
+++ b/crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs
index ecbca81acf4..82c2096a2e4 100644
--- a/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs
+++ b/crates/analytics/src/sdk_events/metrics/sdk_initiated_count.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs
index ed9e776423a..eba94f0d9ad 100644
--- a/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs
+++ b/crates/analytics/src/sdk_events/metrics/sdk_rendered_count.rs
@@ -36,7 +36,8 @@ where
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
- let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEvents);
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
let dimensions = dimensions.to_vec();
for dim in dimensions.iter() {
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 3a1b7f2d468..76ad9c254be 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -542,6 +542,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
Self::Payment => Ok("payment_attempt".to_string()),
Self::Refund => Ok("refund".to_string()),
Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError)
+ .attach_printable("SdkEventsAudit table is not implemented for Sqlx"))?,
+ Self::SdkEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("SdkEvents table is not implemented for Sqlx"))?,
Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ApiEvents table is not implemented for Sqlx"))?,
@@ -550,6 +552,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
.attach_printable("ConnectorEvents table is not implemented for Sqlx"))?,
Self::ApiEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ApiEvents table is not implemented for Sqlx"))?,
+ Self::ActivePaymentsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
+ .attach_printable("ActivePaymentsAnalytics table is not implemented for Sqlx"))?,
Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?,
Self::Dispute => Ok("dispute".to_string()),
@@ -610,6 +614,15 @@ where
alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
)
}
+ Self::DistinctCount { field, alias } => {
+ format!(
+ "count(distinct {}){}",
+ field
+ .to_sql(table_engine)
+ .attach_printable("Failed to distinct count aggregate")?,
+ alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias))
+ )
+ }
})
}
}
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs
index 86a9ec86eff..5370fbc25ac 100644
--- a/crates/analytics/src/types.rs
+++ b/crates/analytics/src/types.rs
@@ -26,12 +26,14 @@ pub enum AnalyticsCollection {
Payment,
Refund,
SdkEvents,
+ SdkEventsAnalytics,
ApiEvents,
PaymentIntent,
ConnectorEvents,
OutgoingWebhookEvent,
Dispute,
ApiEventsAnalytics,
+ ActivePaymentsAnalytics,
}
#[allow(dead_code)]
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index d697c8ab271..491420cfc02 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -4,6 +4,7 @@ use common_utils::pii::EmailStrategy;
use masking::Secret;
use self::{
+ active_payments::ActivePaymentsMetrics,
api_event::{ApiEventDimensions, ApiEventMetrics},
auth_events::AuthEventMetrics,
disputes::{DisputeDimensions, DisputeMetrics},
@@ -13,6 +14,7 @@ use self::{
};
pub use crate::payments::TimeRange;
+pub mod active_payments;
pub mod api_event;
pub mod auth_events;
pub mod connector_events;
@@ -151,6 +153,14 @@ pub struct GetAuthEventMetricRequest {
pub delta: bool,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetActivePaymentsMetricRequest {
+ #[serde(default)]
+ pub metrics: HashSet<ActivePaymentsMetrics>,
+ pub time_range: TimeRange,
+}
+
#[derive(Debug, serde::Serialize)]
pub struct AnalyticsMetadata {
pub current_time_range: TimeRange,
diff --git a/crates/api_models/src/analytics/active_payments.rs b/crates/api_models/src/analytics/active_payments.rs
new file mode 100644
index 00000000000..e7cb2553e01
--- /dev/null
+++ b/crates/api_models/src/analytics/active_payments.rs
@@ -0,0 +1,77 @@
+use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+};
+
+use super::NameDescription;
+
+#[derive(
+ Clone,
+ Debug,
+ Hash,
+ PartialEq,
+ Eq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumIter,
+ strum::AsRefStr,
+)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum ActivePaymentsMetrics {
+ ActivePayments,
+}
+
+pub mod metric_behaviour {
+ pub struct ActivePayments;
+}
+
+impl From<ActivePaymentsMetrics> for NameDescription {
+ fn from(value: ActivePaymentsMetrics) -> Self {
+ Self {
+ name: value.to_string(),
+ desc: String::new(),
+ }
+ }
+}
+
+#[derive(Debug, serde::Serialize, Eq)]
+pub struct ActivePaymentsMetricsBucketIdentifier {
+ pub time_bucket: Option<String>,
+}
+
+impl ActivePaymentsMetricsBucketIdentifier {
+ pub fn new(time_bucket: Option<String>) -> Self {
+ Self { time_bucket }
+ }
+}
+
+impl Hash for ActivePaymentsMetricsBucketIdentifier {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.time_bucket.hash(state);
+ }
+}
+
+impl PartialEq for ActivePaymentsMetricsBucketIdentifier {
+ fn eq(&self, other: &Self) -> bool {
+ let mut left = DefaultHasher::new();
+ self.hash(&mut left);
+ let mut right = DefaultHasher::new();
+ other.hash(&mut right);
+ left.finish() == right.finish()
+ }
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ActivePaymentsMetricsBucketValue {
+ pub active_payments: Option<u64>,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct MetricsBucketResponse {
+ #[serde(flatten)]
+ pub values: ActivePaymentsMetricsBucketValue,
+ #[serde(flatten)]
+ pub dimensions: ActivePaymentsMetricsBucketIdentifier,
+}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 078c27e6db9..bed46f01f19 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -86,6 +86,7 @@ impl_misc_api_event_type!(
GetInfoResponse,
GetPaymentMetricRequest,
GetRefundMetricRequest,
+ GetActivePaymentsMetricRequest,
GetSdkEventMetricRequest,
GetAuthEventMetricRequest,
GetPaymentFiltersRequest,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index b471448368f..80b4e188075 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -12,10 +12,10 @@ pub mod routes {
search::{
GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex,
},
- GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest,
- GetAuthEventMetricRequest, GetDisputeMetricRequest, GetPaymentFiltersRequest,
- GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest,
- GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
+ GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest,
+ GetApiEventMetricRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest,
+ GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest,
+ GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
};
use error_stack::ResultExt;
@@ -70,6 +70,10 @@ pub mod routes {
web::resource("metrics/sdk_events")
.route(web::post().to(get_sdk_event_metrics)),
)
+ .service(
+ web::resource("metrics/active_payments")
+ .route(web::post().to(get_active_payments_metrics)),
+ )
.service(
web::resource("filters/sdk_events")
.route(web::post().to(get_sdk_event_filters)),
@@ -245,6 +249,43 @@ pub mod routes {
.await
}
+ /// # Panics
+ ///
+ /// Panics if `json_payload` array does not contain one `GetActivePaymentsMetricRequest` element.
+ pub async fn get_active_payments_metrics(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<[GetActivePaymentsMetricRequest; 1]>,
+ ) -> impl Responder {
+ // safety: This shouldn't panic owing to the data type
+ #[allow(clippy::expect_used)]
+ let payload = json_payload
+ .into_inner()
+ .to_vec()
+ .pop()
+ .expect("Couldn't get GetActivePaymentsMetricRequest");
+ let flow = AnalyticsFlow::GetActivePaymentsMetrics;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: AuthenticationData, req, _| async move {
+ analytics::active_payments::get_metrics(
+ &state.pool,
+ auth.merchant_account.publishable_key.as_ref(),
+ Some(&auth.merchant_account.merchant_id),
+ req,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element.
diff --git a/docker-compose.yml b/docker-compose.yml
index aff7ab54f45..569ef045064 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -164,8 +164,8 @@ services:
- HYPERSWITCH_CLIENT_URL=http://localhost:9050
- SELF_SERVER_URL=http://localhost:5252
- SDK_ENV=local
- - ENV_LOGGING_URL=http://localhost:3100
- labels:
+ - ENV_LOGGING_URL=http://localhost:3103
+ labels:
logs: "promtail"
### Control Center
@@ -405,6 +405,7 @@ services:
ports:
- "8686"
- "9598"
+ - "3103:3103"
profiles:
- olap
environment:
|
2024-06-24T11:00: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 -->
This PR introduces a real-time analytics feature that allows merchants to track distinct payment IDs on their dashboards. The key components of this feature include a script to create a ClickHouse table with a 1-minute Time-To-Live (TTL) for the data, and an analytics service that counts distinct payment IDs.
Also add the the http server for vector to collect and push logs to kafka in this PR.
## Changes:
**ClickHouse Table Creation Script:**
Added a script to create a ClickHouse table with a 1-minute TTL. This table will store payment events and automatically purge entries older than 1 minute, ensuring that only recent data is kept for real-time analytics.
**Analytics Service:**
Implemented an analytics service that queries the ClickHouse table to count distinct payment IDs. This provides real-time insights into the number of unique payments processed within the last minute.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
**1. Start the necessary services using Docker Compose**
```
docker compose up -d kafka-ui clickhouse-server
```
**2. Load the SDK and simulate payments**
**3. Verify Real-Time Analytics**
```
curl --location 'localhost:8080/analytics/v1/metrics/active_payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {token}' \
--data '[
{
"timeRange": {
"startTime": "2024-06-24T18:30:00Z",
"endTime": "2024-06-24T18:31:00Z"
},
"metrics": [
"active_payments"
]
}
]'
```
```
{
"queryData": [
{
"active_payments": 2
}
],
"metaData": [
{
"current_time_range": {
"start_time": "2024-06-24T18:30:00Z",
"end_time": "2024-06-24T18:31:00Z"
}
}
]
}
```
## Checklist
<!-- Put 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
|
ea74f3e537aca44c42bd1e9c80eb7a1e220c295d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4325
|
Bug: feat: Role information in list merchants API
- HCC FE is building a profile feature where they want to show all the merchants where the current user is part of.
- This also includes the role they were assigned in each merchant account.
- We have an API which lists merchant accounts but it doesn't send role they were assigned.
- So, we can change that API to also send the roles.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 9b193a9ba12..afe55afb276 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -190,6 +190,9 @@ pub struct UserMerchantAccount {
pub merchant_id: String,
pub merchant_name: OptionalEncryptableName,
pub is_active: bool,
+ pub role_id: String,
+ pub role_name: String,
+ pub org_id: String,
}
#[cfg(feature = "recon")]
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 2702cec8eb5..50fd094d8d0 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1173,7 +1173,7 @@ pub async fn create_merchant_account(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn list_merchant_ids_for_user(
+pub async fn list_merchants_for_user(
state: AppState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
@@ -1194,8 +1194,15 @@ pub async fn list_merchant_ids_for_user(
.await
.change_context(UserErrors::InternalServerError)?;
+ let roles =
+ utils::user_role::get_multiple_role_info_for_user_roles(&state, &user_roles).await?;
+
Ok(ApplicationResponse::Json(
- utils::user::get_multiple_merchant_details_with_status(user_roles, merchant_accounts)?,
+ utils::user::get_multiple_merchant_details_with_status(
+ user_roles,
+ merchant_accounts,
+ roles,
+ )?,
))
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 41893b05445..e0e3045aa8a 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1135,7 +1135,9 @@ impl User {
web::resource("/create_merchant")
.route(web::post().to(user_merchant_account_create)),
)
- .service(web::resource("/switch/list").route(web::get().to(list_merchant_ids_for_user)))
+ // TODO: Remove this endpoint once migration to /merchants/list is done
+ .service(web::resource("/switch/list").route(web::get().to(list_merchants_for_user)))
+ .service(web::resource("/merchants/list").route(web::get().to(list_merchants_for_user)))
.service(web::resource("/permission_info").route(web::get().to(get_authorization_info)))
.service(web::resource("/update").route(web::post().to(update_user_account_details)))
.service(
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index c296d3d93b3..3e5061b401d 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -297,17 +297,14 @@ pub async fn delete_sample_data(
.await
}
-pub async fn list_merchant_ids_for_user(
- state: web::Data<AppState>,
- req: HttpRequest,
-) -> HttpResponse {
+pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::UserMerchantAccountList;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
- |state, user, _| user_core::list_merchant_ids_for_user(state, user),
+ |state, user, _| user_core::list_merchants_for_user(state, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 93df373d21a..bc06ffbad7b 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -896,9 +896,14 @@ impl SignInWithMultipleRolesStrategy {
.await
.change_context(UserErrors::InternalServerError)?;
+ let roles =
+ utils::user_role::get_multiple_role_info_for_user_roles(state, &self.user_roles)
+ .await?;
+
let merchant_details = utils::user::get_multiple_merchant_details_with_status(
self.user_roles,
merchant_accounts,
+ roles,
)?;
Ok(user_api::SignInResponse::MerchantSelect(
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index f8b7d86c74a..60b2ac48286 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use api_models::user as user_api;
use common_utils::errors::CustomResult;
use diesel_models::{enums::UserStatus, user_role::UserRole};
-use error_stack::{report, ResultExt};
+use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use crate::{
@@ -137,24 +137,38 @@ pub fn get_verification_days_left(
pub fn get_multiple_merchant_details_with_status(
user_roles: Vec<UserRole>,
merchant_accounts: Vec<MerchantAccount>,
+ roles: Vec<RoleInfo>,
) -> UserResult<Vec<user_api::UserMerchantAccount>> {
- let roles: HashMap<_, _> = user_roles
+ let merchant_account_map = merchant_accounts
.into_iter()
- .map(|user_role| (user_role.merchant_id.clone(), user_role))
- .collect();
+ .map(|merchant_account| (merchant_account.merchant_id.clone(), merchant_account))
+ .collect::<HashMap<_, _>>();
- merchant_accounts
+ let role_map = roles
.into_iter()
- .map(|merchant| {
- let role = roles
- .get(merchant.merchant_id.as_str())
- .ok_or(report!(UserErrors::InternalServerError))
- .attach_printable("Merchant exists but user role doesn't")?;
+ .map(|role_info| (role_info.get_role_id().to_string(), role_info))
+ .collect::<HashMap<_, _>>();
+
+ user_roles
+ .into_iter()
+ .map(|user_role| {
+ let merchant_account = merchant_account_map
+ .get(&user_role.merchant_id)
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Merchant account for user role doesn't exist")?;
+
+ let role_info = role_map
+ .get(&user_role.role_id)
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Role info for user role doesn't exist")?;
Ok(user_api::UserMerchantAccount {
- merchant_id: merchant.merchant_id.clone(),
- merchant_name: merchant.merchant_name.clone(),
- is_active: role.status == UserStatus::Active,
+ merchant_id: user_role.merchant_id,
+ merchant_name: merchant_account.merchant_name.clone(),
+ is_active: user_role.status == UserStatus::Active,
+ role_id: user_role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ org_id: user_role.org_id,
})
})
.collect()
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 1a52153b43d..ba4c2878667 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -8,7 +8,7 @@ use router_env::logger;
use crate::{
consts,
- core::errors::{UserErrors, UserResult},
+ core::errors::{StorageErrorExt, UserErrors, UserResult},
routes::AppState,
services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
@@ -141,3 +141,22 @@ pub async fn set_role_permissions_in_cache_if_required(
.change_context(UserErrors::InternalServerError)
.attach_printable("Error setting permissions in redis")
}
+
+pub async fn get_multiple_role_info_for_user_roles(
+ state: &AppState,
+ user_roles: &[UserRole],
+) -> UserResult<Vec<roles::RoleInfo>> {
+ futures::future::try_join_all(user_roles.iter().map(|user_role| async {
+ let role = roles::RoleInfo::from_role_id(
+ state,
+ &user_role.role_id,
+ &user_role.merchant_id,
+ &user_role.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InternalServerError)
+ .attach_printable("Role for user role doesn't exist")?;
+ Ok::<_, error_stack::Report<UserErrors>>(role)
+ }))
+ .await
+}
|
2024-04-08T07:16:14Z
|
## 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 `role_id`, `role_name`, `org_id` fields in list merchants for user API.
- New route `/user/merchants/list` which points to the same function as `/user/switch/list`.
### 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 #4325.
## How did you test 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.
Both the following endpoints should produce the same results.
```
curl --location 'http://localhost:8080/user/merchants/list' \
--header 'Authorization: Bearer JWT' \
--header 'Cookie: login_token=JWT'
```
```
curl --location 'http://localhost:8080/user/switch/list' \
--header 'Authorization: Bearer JWT' \
--header 'Cookie: login_token=JWT'
```
Response: Should list all the merchant accounts that user is part of with the following structure.
```
[
{
"merchant_id": "merchant_1712559091",
"merchant_name": null,
"is_active": true,
"role_id": "org_admin",
"role_name": "organization_admin",
"org_id": "org_NUwiY2HO9JRffXuYrJAx"
},
{
"merchant_id": "merchant_1712559763",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_view_only",
"role_name": "view_only",
"org_id": "org_do8JuIQiH0tDQtWly4xo"
}
]
```
## Checklist
<!-- Put an `x` in 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
|
433b4bbf278b95be6c3f1d5f4749cf765b664e80
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4322
|
Bug: fix(psync): log the error if payment method retrieve fails in the `psync flow`
-> When a payment is created with save card we store the card in the locker and also a payment method entry is created in the payment method table. And the corresponding `payment_method_id` will be stored in the `payment_attempt` table.
-> And later when that payment method is deleted, psycn is failing as we are trying to fetch the payment method data from the payment_method table in the psync flow.
-> The error occurred because of the recent change that was trying to fetch the payment method in the psync flow using the payment_method_id in the payment attempt.
This can be fixed by adding a validation for the error that occurs during fetching the payment method data from the db. If it is not found in db error then just log the error (do not propagate it), any other error needs to be returned as it is.
|
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 7a8f487d73a..f25b89977f6 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -5,7 +5,7 @@ use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
-use router_env::{instrument, tracing};
+use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
@@ -399,14 +399,22 @@ async fn get_tracker_for_sync<
.to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
id: profile_id.to_string(),
})?;
+
let payment_method_info =
if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() {
- Some(
- db.find_payment_method(payment_method_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
- .attach_printable("error retrieving payment method from DB")?,
- )
+ match db.find_payment_method(payment_method_id).await {
+ Ok(payment_method) => Some(payment_method),
+ Err(error) => {
+ if error.current_context().is_db_not_found() {
+ logger::info!("Payment Method not found in db {:?}", error);
+ None
+ } else {
+ Err(error)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error retrieving payment method from db")?
+ }
+ }
+ }
} else {
None
};
|
2024-04-07T15:10:35Z
|
## 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 -->
-> When a payment is created with save card we store the card in the locker and also a payment method entry is created in the payment method table. And the corresponding payment_method_id will be stored in the payment_attempt table.
-> And later when that payment method is deleted, psycn is failing as we are trying to fetch the payment method data from the payment_method table in the psync flow.
-> The error occurred because of the recent change that was trying to fetch the payment method in the psync flow using the payment_method_id in the payment attempt.
This is fixed by adding a validation for the error that occurs during fetching the payment method data from the db. If it is not found in db error then just log the error (do not propagate it), any other error needs to be returned as it is.
### 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 payment with save card
<img width="1101" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/08e7e91f-c395-49f3-811c-f78fa79e4c92">
```
{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "aaa",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"setup_future_usage": "on_session",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Delete the saved payment mehtod
```
curl --location --request DELETE 'http://localhost:8080/payment_methods/{{pm_id}}' \
--header 'Accept: application/json' \
--header 'api-key: abc'
```
payment method entry being deleted from db
<img width="1124" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/7251dffc-e358-4b3d-86e3-f2209c83964d">
Retrieve the above payment
```
curl --location 'http://localhost:8080/payments/pay_7VFY24kczcTpt0xQfU8M?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_uU4PZwC903VYtQnTBvTxgU0QFDmah0mcPN5qehIq7tS0oapEfBBVp96oaIHyjDdM'
```
<img width="1035" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/b518693a-7544-4342-9da6-51057ca06384">
## Checklist
<!-- Put an `x` in 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
|
7c62dd1c4ba3c67ac86d638227f04e4a1ed5db2d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4306
|
Bug: fix(mandate): add validation for currency in MIT recurring payments
When a setup_mandate is done with currency say `USD`, When a recurring payment is being made using `payment_method_id` with another currency, the payment should fail saying `cross currency mandates not supported`
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 22f7cb311c6..b8326874abc 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -21,7 +21,7 @@ use api_models::{
use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge};
use data_models::mandates::{CustomerAcceptance, MandateData};
use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
-use error_stack::ResultExt;
+use error_stack::{report, ResultExt};
use futures::future::join_all;
use helpers::ApplePayData;
use masking::Secret;
@@ -3097,6 +3097,17 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
.attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?
.get(merchant_connector_id)
{
+ common_utils::fp_utils::when(
+ mandate_reference_record
+ .original_payment_authorized_currency
+ .map(|mandate_currency| mandate_currency != payment_data.currency)
+ .unwrap_or(false),
+ || {
+ Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
+ reason: "cross currency mandates not supported".into()
+ }))
+ },
+ )?;
let mandate_reference_id =
Some(payments_api::MandateReferenceId::ConnectorMandateId(
payments_api::ConnectorMandateReferenceId {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 6ede6ad899a..2c98052ad3d 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -13,7 +13,7 @@ use diesel_models::{ephemeral_key, PaymentMethod};
use error_stack::{self, ResultExt};
use masking::{ExposeInterface, PeekInterface};
use router_derive::PaymentOperation;
-use router_env::{instrument, tracing};
+use router_env::{instrument, logger, tracing};
use time::PrimitiveDateTime;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
@@ -782,12 +782,20 @@ impl PaymentCreate {
key_store.key.get_inner().peek(),
)
.await
- .change_context(errors::StorageError::DecryptionError)
- .attach_printable("unable to decrypt card details")
+ .map_err(|err| logger::error!("Failed to decrypt card details: {:?}", err))
.ok()
.flatten()
.map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|v| {
+ serde_json::from_value::<PaymentMethodsData>(v)
+ .map_err(|err| {
+ logger::error!(
+ "Unable to deserialize payment methods data: {:?}",
+ err
+ )
+ })
+ .ok()
+ })
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
|
2024-04-04T14:54:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
When a setup_mandate is done with currency say `USD`, When a recurring payment is being made using `payment_method_id` with another currency, the payment should fail saying `cross currency mandates not supported`.
This PR also handles error which could occur during payment_method_data decryption
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Setup mandate with a customer
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "test_cus4",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "online"
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"card_cvc": "737"
}
},
"payment_type": "setup_mandate",
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "153.54.53.134",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": null
}
}
}'
```
2. Now try to do recurring payment using`payment_method_id` by passing different currency
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 499,
"currency": "EUR",
"confirm": true,
"capture_method": "automatic",
"customer_id": "test_cus5",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "xyz"
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds"
}'
```

## Checklist
<!-- Put an `x` in 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
|
071462f2af8efeb16e48d351bbae68fd2fd64179
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4319
|
Bug: store network transaction id only when pg_agnostic config is enabled in the authorize_flow
Currently there is no validation while storing the network transaction id in the authorize flow. As network transaction is only being used for the processor agnostic MITs it should be stored only if the `pg_agnostic` flag is enabled.
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 7d1862b2068..e22942fecd6 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2664,12 +2664,23 @@ impl<F, T>
item.response.id.clone(),
))
} else {
+ let network_transaction_id = match item.response.latest_charge.clone() {
+ Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
+ .payment_method_details
+ .and_then(|payment_method_details| match payment_method_details {
+ StripePaymentMethodDetailsResponse::Card { card } => {
+ card.network_transaction_id
+ }
+ _ => None,
+ }),
+ _ => None,
+ };
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
mandate_reference,
connector_metadata,
- network_txn_id: None,
+ network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id.clone()),
incremental_authorization_allowed: None,
})
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 22f7cb311c6..91b1d7f3190 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1347,6 +1347,7 @@ where
merchant_account,
connector_request,
key_store,
+ payment_data.payment_intent.profile_id.clone(),
)
.await
} else {
@@ -1475,6 +1476,7 @@ where
merchant_account,
None,
key_store,
+ payment_data.payment_intent.profile_id.clone(),
);
join_handlers.push(res);
@@ -3069,6 +3071,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
connector_data.connector_name,
payment_method_info,
) {
+ logger::info!("using network_transaction_id for MIT flow");
let network_transaction_id = payment_method_info
.network_transaction_id
.as_ref()
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 6c952dc2593..abe23016f7d 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -49,6 +49,7 @@ pub trait Feature<F, T> {
merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
key_store: &domain::MerchantKeyStore,
+ profile_id: Option<String>,
) -> 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 14b710de914..43e36847eb9 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -54,6 +54,7 @@ impl Feature<api::Approve, types::PaymentsApproveData>
_merchant_account: &domain::MerchantAccount,
_connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> 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 f891f44f099..cccfab5a74b 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -66,6 +66,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
key_store: &domain::MerchantKeyStore,
+ profile_id: Option<String>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
@@ -103,6 +104,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
key_store,
Some(resp.request.amount),
Some(resp.request.currency),
+ profile_id,
))
.await?;
@@ -132,6 +134,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
key_store,
Some(resp.request.amount),
Some(resp.request.currency),
+ profile_id,
))
.await;
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 5918380ee0b..5814b1cafb1 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -53,6 +53,7 @@ impl Feature<api::Void, types::PaymentsCancelData>
_merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> 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 d2b7c8e91bd..5f64014bce7 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -54,6 +54,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
_merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> 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 68d0ee8d475..e64240387d2 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -68,6 +68,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
_merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
index 387916bab7c..99f8e4831bb 100644
--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
@@ -61,6 +61,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat
_merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> 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 cb7a764985d..6463e87279b 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -57,6 +57,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>
_merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> 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 910cc955e63..4157edf8d0a 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -53,6 +53,7 @@ impl Feature<api::Reject, types::PaymentsRejectData>
_merchant_account: &domain::MerchantAccount,
_connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> 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 349c76cd23a..1ab72dff15b 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -58,6 +58,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
_merchant_account: &domain::MerchantAccount,
_connector_request: Option<services::Request>,
_key_store: &domain::MerchantKeyStore,
+ _profile_id: Option<String>,
) -> RouterResult<Self> {
metrics::SESSION_TOKEN_CREATED.add(
&metrics::CONTEXT,
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 27204450a0a..d8acfe98f3b 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -62,6 +62,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
key_store: &domain::MerchantKeyStore,
+ profile_id: Option<String>,
) -> RouterResult<Self> {
if let Some(mandate_id) = self
.request
@@ -79,6 +80,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
&state.conf.mandates.update_mandate_supported,
connector_request,
maybe_customer,
+ profile_id,
))
.await
} else {
@@ -109,6 +111,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
key_store,
resp.request.amount,
Some(resp.request.currency),
+ profile_id,
))
.await?;
@@ -217,6 +220,7 @@ impl types::SetupMandateRouterData {
call_connector_action: payments::CallConnectorAction,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
+ profile_id: Option<String>,
) -> RouterResult<Self> {
match confirm {
Some(true) => {
@@ -248,6 +252,7 @@ impl types::SetupMandateRouterData {
key_store,
resp.request.amount,
Some(resp.request.currency),
+ profile_id,
))
.await?;
@@ -278,6 +283,7 @@ impl types::SetupMandateRouterData {
supported_connectors_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
connector_request: Option<services::Request>,
maybe_customer: &Option<domain::Customer>,
+ profile_id: Option<String>,
) -> RouterResult<Self> {
let payment_method_type = self.request.payment_method_type;
@@ -336,6 +342,7 @@ impl types::SetupMandateRouterData {
key_store,
resp.request.amount,
Some(resp.request.currency),
+ profile_id,
))
.await?
.0;
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 70cf702311d..aeb4d6e5b1c 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1001,12 +1001,13 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The pg_agnostic config was not found in the DB")?;
- if &pg_agnostic.config == "true" {
+ if &pg_agnostic.config == "true"
+ && payment_data.payment_intent.setup_future_usage
+ == Some(diesel_models::enums::FutureUsage::OffSession)
+ {
Some(network_transaction_id)
} else {
- logger::info!(
- "Skip storing network transaction id as pg_agnostic config is not enabled"
- );
+ logger::info!("Skip storing network transaction id");
None
}
} else {
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 47cd1cd9eb7..3f24c55c998 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -41,6 +41,7 @@ pub async fn save_payment_method<F: Clone, FData>(
key_store: &domain::MerchantKeyStore,
amount: Option<i64>,
currency: Option<storage_enums::Currency>,
+ profile_id: Option<String>,
) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
where
FData: mandate::MandateBehaviour,
@@ -64,6 +65,35 @@ where
_ => None,
};
+ let network_transaction_id =
+ if let Some(network_transaction_id) = network_transaction_id {
+ let profile_id = profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let pg_agnostic = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &format!("pg_agnostic_mandate_{}", profile_id),
+ Some("false".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("The pg_agnostic config was not found in the DB")?;
+
+ if &pg_agnostic.config == "true"
+ && resp.request.get_setup_future_usage()
+ == Some(storage_enums::FutureUsage::OffSession)
+ {
+ Some(network_transaction_id)
+ } else {
+ logger::info!("Skip storing network transaction id");
+ None
+ }
+ } else {
+ None
+ };
+
let connector_token = if token_store {
let tokens = resp
.payment_method_token
|
2024-04-05T13:00:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently there is no validation while storing the network transaction id in the authorize flow. As network transaction is only being used for the processor agnostic MITs it should be stored (in `payment_methods` table) only if the pg_agnostic flag is enabled.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
`payment_method` table where `network_transaction_id` is null as `pg_agnotic` flag is not enabled.
<img width="1456" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c2b1971e-97fc-4da2-9d72-df656ae79bf2">
enabled `pg_agnotic` flag
```
curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT_Token' \
--data '{
"enabled": true
}'
```
Preform a setup_mandate
```
{
"amount": 1000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "ajjj",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
<img width="1080" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f657c6f5-dda0-4f5c-958c-435774255af8">
Network transaction id being stored after the pg_agnotic flag is enabled.
<img width="1424" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/eec4bdfc-caf2-4572-a8ba-bdba32974873">
## Checklist
<!-- Put an `x` in 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
|
669485275db192b0e8e30f3528c0d61150d91847
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4304
|
Bug: refactor(payment_methods): revamp payment methods update endpoint
`/payment_methods/update` endpoint doesn't currently perform the expected functionality. Revamp the endpoint such that
- It deletes the existing entry from locker.
- Create a new updated payment method and store it in locker
- Update the existing payment methods entry in Hyperswitch
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index dd6495bb979..7eb7e213e5b 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -76,7 +76,7 @@ pub struct PaymentMethodUpdate {
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "John Doe"}))]
- pub card: Option<CardDetail>,
+ pub card: Option<CardDetailUpdate>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<CardNetwork>,example = "Visa")]
@@ -95,6 +95,10 @@ pub struct PaymentMethodUpdate {
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
+ #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
+ pub client_secret: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
@@ -134,6 +138,54 @@ pub struct CardDetail {
pub card_type: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct CardDetailUpdate {
+ /// Card Expiry Month
+ #[schema(value_type = String,example = "10")]
+ pub card_exp_month: Option<masking::Secret<String>>,
+
+ /// Card Expiry Year
+ #[schema(value_type = String,example = "25")]
+ pub card_exp_year: Option<masking::Secret<String>>,
+
+ /// Card Holder Name
+ #[schema(value_type = String,example = "John Doe")]
+ pub card_holder_name: Option<masking::Secret<String>>,
+
+ /// Card Holder's Nick Name
+ #[schema(value_type = Option<String>,example = "John Doe")]
+ pub nick_name: Option<masking::Secret<String>>,
+}
+
+impl CardDetailUpdate {
+ pub fn apply(&self, card_data_from_locker: Card) -> CardDetail {
+ CardDetail {
+ card_number: card_data_from_locker.card_number,
+ card_exp_month: self
+ .card_exp_month
+ .clone()
+ .unwrap_or(card_data_from_locker.card_exp_month),
+ card_exp_year: self
+ .card_exp_year
+ .clone()
+ .unwrap_or(card_data_from_locker.card_exp_year),
+ card_holder_name: self
+ .card_holder_name
+ .clone()
+ .or(card_data_from_locker.name_on_card),
+ nick_name: self
+ .nick_name
+ .clone()
+ .or(card_data_from_locker.nick_name.map(masking::Secret::new)),
+ card_issuing_country: None,
+ card_network: None,
+ card_issuer: None,
+ card_type: None,
+ }
+ }
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponse {
/// Unique identifier for a merchant
@@ -242,6 +294,17 @@ pub struct BankAccountConnectorDetails {
pub enum BankAccountAccessCreds {
AccessToken(masking::Secret<String>),
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct Card {
+ pub card_number: CardNumber,
+ pub name_on_card: Option<masking::Secret<String>>,
+ pub card_exp_month: masking::Secret<String>,
+ pub card_exp_year: masking::Secret<String>,
+ pub card_brand: Option<String>,
+ pub card_isin: Option<String>,
+ pub nick_name: Option<String>,
+}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct CardDetailFromLocker {
pub scheme: Option<String>,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index c9114cb1348..97927d5707f 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -204,6 +204,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::CardDetail,
+ api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c885a3bf227..9a58f606f6d 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -7,8 +7,8 @@ use api_models::{
admin::{self, PaymentMethodsEnabled},
enums::{self as api_enums},
payment_methods::{
- BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName,
- CustomerDefaultPaymentMethodResponse, ListCountriesCurrenciesRequest,
+ BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
+ CountryCodeWithName, CustomerDefaultPaymentMethodResponse, ListCountriesCurrenciesRequest,
ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes,
PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
@@ -44,10 +44,7 @@ use crate::{
configs::settings,
core::{
errors::{self, StorageErrorExt},
- payment_methods::{
- transformers::{self as payment_methods},
- vault,
- },
+ payment_methods::{transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
@@ -270,10 +267,18 @@ pub async fn add_payment_method(
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
- add_card_to_locker(&state, req.clone(), &card, &customer_id, merchant_account)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Add Card Failed")
+ helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
+ add_card_to_locker(
+ &state,
+ req.clone(),
+ &card,
+ &customer_id,
+ merchant_account,
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Add Card Failed")
}
_ => Ok(store_default_payment_method(
&req,
@@ -472,47 +477,229 @@ pub async fn update_customer_payment_method(
payment_method_id: &str,
key_store: domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
- let db = state.store.as_ref();
- let pm = db
- .delete_payment_method_by_merchant_id_payment_method_id(
- &merchant_account.merchant_id,
- payment_method_id,
+ // Currently update is supported only for cards
+ if let Some(card_update) = req.card.clone() {
+ let db = state.store.as_ref();
+
+ let pm = db
+ .find_payment_method(payment_method_id, merchant_account.storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ // Fetch the existing payment method data from db
+ let existing_card_data = decrypt::<serde_json::Value, masking::WithType>(
+ pm.payment_method_data.clone(),
+ key_store.key.get_inner().peek(),
)
.await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- if pm.payment_method == enums::PaymentMethod::Card {
- delete_card_from_locker(
- &state,
- &pm.customer_id,
- &pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to decrypt card details")?
+ .map(|x| x.into_inner().expose())
+ .map(
+ |value| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
+ value
+ .parse_value::<PaymentMethodsData>("PaymentMethodsData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize payment methods data")
+ },
)
- .await?;
- };
- let new_pm = api::PaymentMethodCreate {
- payment_method: pm.payment_method,
- payment_method_type: pm.payment_method_type,
- payment_method_issuer: pm.payment_method_issuer,
- payment_method_issuer_code: pm.payment_method_issuer_code,
- #[cfg(feature = "payouts")]
- bank_transfer: req.bank_transfer,
- card: req.card,
- #[cfg(feature = "payouts")]
- wallet: req.wallet,
- metadata: req.metadata,
- customer_id: Some(pm.customer_id),
- card_network: req
- .card_network
- .as_ref()
- .map(|card_network| card_network.to_string()),
- };
- Box::pin(add_payment_method(
- state,
- new_pm,
- &merchant_account,
- &key_store,
- ))
- .await
+ .transpose()?
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ })
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to obtain decrypted card object from db")?;
+
+ let is_card_updation_required =
+ validate_payment_method_update(card_update.clone(), existing_card_data.clone());
+
+ let response = if is_card_updation_required {
+ // Fetch the existing card data from locker for getting card number
+ let card_data_from_locker = get_card_from_locker(
+ &state,
+ &pm.customer_id,
+ &pm.merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error getting card from locker")?;
+
+ if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() {
+ helpers::validate_card_expiry(
+ card_update
+ .card_exp_month
+ .as_ref()
+ .unwrap_or(&card_data_from_locker.card_exp_month),
+ card_update
+ .card_exp_year
+ .as_ref()
+ .unwrap_or(&card_data_from_locker.card_exp_year),
+ )?;
+ }
+
+ let updated_card_details = card_update.apply(card_data_from_locker.clone());
+
+ // Construct new payment method object from request
+ let new_pm = api::PaymentMethodCreate {
+ payment_method: pm.payment_method,
+ payment_method_type: pm.payment_method_type,
+ payment_method_issuer: pm.payment_method_issuer.clone(),
+ payment_method_issuer_code: pm.payment_method_issuer_code,
+ #[cfg(feature = "payouts")]
+ bank_transfer: req.bank_transfer,
+ card: Some(updated_card_details.clone()),
+ #[cfg(feature = "payouts")]
+ wallet: req.wallet,
+ metadata: req.metadata,
+ customer_id: Some(pm.customer_id.clone()),
+ card_network: req
+ .card_network
+ .as_ref()
+ .map(|card_network| card_network.to_string()),
+ };
+ new_pm.validate()?;
+
+ // Delete old payment method from locker
+ delete_card_from_locker(
+ &state,
+ &pm.customer_id,
+ &pm.merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await?;
+
+ // Add the updated payment method data to locker
+ let (mut add_card_resp, _) = add_card_to_locker(
+ &state,
+ new_pm.clone(),
+ &updated_card_details,
+ &pm.customer_id,
+ &merchant_account,
+ Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add updated payment method to locker")?;
+
+ // Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data
+ let updated_card = Some(api::CardDetailFromLocker {
+ scheme: existing_card_data.scheme,
+ last4_digits: Some(card_data_from_locker.card_number.clone().get_last4()),
+ issuer_country: existing_card_data.issuer_country,
+ card_number: existing_card_data.card_number,
+ expiry_month: card_update
+ .card_exp_month
+ .or(existing_card_data.expiry_month),
+ expiry_year: card_update.card_exp_year.or(existing_card_data.expiry_year),
+ card_token: existing_card_data.card_token,
+ card_fingerprint: existing_card_data.card_fingerprint,
+ card_holder_name: card_update
+ .card_holder_name
+ .or(existing_card_data.card_holder_name),
+ nick_name: card_update.nick_name.or(existing_card_data.nick_name),
+ card_network: existing_card_data.card_network,
+ card_isin: existing_card_data.card_isin,
+ card_issuer: existing_card_data.card_issuer,
+ card_type: existing_card_data.card_type,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card
+ .as_ref()
+ .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(&key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
+
+ add_card_resp.payment_method_id = pm.payment_method_id.clone();
+
+ db.update_payment_method(pm, pm_update, merchant_account.storage_scheme)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ add_card_resp
+ } else {
+ // Return existing payment method data as response without any changes
+ api::PaymentMethodResponse {
+ merchant_id: pm.merchant_id.to_owned(),
+ customer_id: Some(pm.customer_id),
+ payment_method_id: pm.payment_method_id,
+ payment_method: pm.payment_method,
+ payment_method_type: pm.payment_method_type,
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ card: Some(existing_card_data),
+ metadata: pm.metadata,
+ created: Some(pm.created_at),
+ recurring_enabled: false,
+ installment_payment_enabled: false,
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()),
+ }
+ };
+
+ Ok(services::ApplicationResponse::Json(response))
+ } else {
+ Err(report!(errors::ApiErrorResponse::NotSupported {
+ message: "Payment method update for the given payment method is not supported".into()
+ }))
+ }
+}
+
+pub fn validate_payment_method_update(
+ card_updation_obj: CardDetailUpdate,
+ existing_card_data: api::CardDetailFromLocker,
+) -> bool {
+ // Return true If any one of the below condition returns true,
+ // If a field is not passed in the update request, return false.
+ // If the field is present, it depends on the existing field data:
+ // - If existing field data is not present, or if it is present and doesn't match
+ // the update request data, then return true.
+ // - Or else return false
+ card_updation_obj
+ .card_exp_month
+ .map(|exp_month| exp_month.expose())
+ .map_or(false, |new_exp_month| {
+ existing_card_data
+ .expiry_month
+ .map(|exp_month| exp_month.expose())
+ .map_or(true, |old_exp_month| new_exp_month != old_exp_month)
+ })
+ || card_updation_obj
+ .card_exp_year
+ .map(|exp_year| exp_year.expose())
+ .map_or(false, |new_exp_year| {
+ existing_card_data
+ .expiry_year
+ .map(|exp_year| exp_year.expose())
+ .map_or(true, |old_exp_year| new_exp_year != old_exp_year)
+ })
+ || card_updation_obj
+ .card_holder_name
+ .map(|name| name.expose())
+ .map_or(false, |new_card_holder_name| {
+ existing_card_data
+ .card_holder_name
+ .map(|name| name.expose())
+ .map_or(true, |old_card_holder_name| {
+ new_card_holder_name != old_card_holder_name
+ })
+ })
+ || card_updation_obj
+ .nick_name
+ .map(|nick_name| nick_name.expose())
+ .map_or(false, |new_nick_name| {
+ existing_card_data
+ .nick_name
+ .map(|nick_name| nick_name.expose())
+ .map_or(true, |old_nick_name| new_nick_name != old_nick_name)
+ })
}
// Wrapper function to switch lockers
@@ -588,6 +775,7 @@ pub async fn add_card_to_locker(
card: &api::CardDetail,
customer_id: &String,
merchant_account: &domain::MerchantAccount,
+ card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
@@ -605,7 +793,7 @@ pub async fn add_card_to_locker(
customer_id.to_string(),
merchant_account,
api_enums::LockerChoice::HyperswitchCardVault,
- None,
+ card_reference,
)
.await
.map_err(|error| {
@@ -634,7 +822,7 @@ pub async fn get_card_from_locker(
customer_id: &str,
merchant_id: &str,
card_reference: &str,
-) -> errors::RouterResult<payment_methods::Card> {
+) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]);
let get_card_from_rs_locker_resp = request::record_operation_time(
@@ -713,7 +901,7 @@ pub async fn add_card_hs(
merchant_id: &merchant_account.merchant_id,
merchant_customer_id: customer_id.to_owned(),
requestor_card_reference: card_reference.map(str::to_string),
- card: payment_methods::Card {
+ card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.card_exp_month.to_owned(),
@@ -899,7 +1087,7 @@ pub async fn get_card_from_hs_locker<'a>(
merchant_id: &str,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
-) -> errors::CustomResult<payment_methods::Card, errors::VaultError> {
+) -> errors::CustomResult<Card, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 357f077332d..a9671cc6783 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -1,6 +1,6 @@
use std::str::FromStr;
-use api_models::enums as api_enums;
+use api_models::{enums as api_enums, payment_methods::Card};
use common_utils::{
ext_traits::{Encode, StringExt},
pii::Email,
@@ -53,17 +53,6 @@ pub struct StoreGenericReq<'a> {
pub enc_data: String,
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct Card {
- pub card_number: cards::CardNumber,
- pub name_on_card: Option<Secret<String>>,
- pub card_exp_month: Secret<String>,
- pub card_exp_year: Secret<String>,
- pub card_brand: Option<String>,
- pub card_isin: Option<String>,
- pub nick_name: Option<String>,
-}
-
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardResp {
pub status: String,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 9851ec1edc2..ad3773cb7c6 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -799,47 +799,57 @@ pub fn validate_card_data(
},
)?;
- let exp_month = card
- .card_exp_month
- .peek()
- .to_string()
- .parse::<u8>()
+ validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
+ }
+ Ok(())
+}
+
+#[instrument(skip_all)]
+pub fn validate_card_expiry(
+ card_exp_month: &masking::Secret<String>,
+ card_exp_year: &masking::Secret<String>,
+) -> CustomResult<(), errors::ApiErrorResponse> {
+ let exp_month = card_exp_month
+ .peek()
+ .to_string()
+ .parse::<u8>()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "card_exp_month",
+ })?;
+ let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message: "Invalid Expiry Month".to_string(),
+ },
+ )?;
+
+ let mut year_str = card_exp_year.peek().to_string();
+ if year_str.len() == 2 {
+ year_str = format!("20{}", year_str);
+ }
+ let exp_year =
+ year_str
+ .parse::<u16>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "card_exp_month",
+ field_name: "card_exp_year",
})?;
- let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(
- errors::ApiErrorResponse::PreconditionFailed {
- message: "Invalid Expiry Month".to_string(),
- },
- )?;
- let mut year_str = card.card_exp_year.peek().to_string();
- if year_str.len() == 2 {
- year_str = format!("20{}", year_str);
- }
- let exp_year =
- year_str
- .parse::<u16>()
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "card_exp_year",
- })?;
- let year = ::cards::CardExpirationYear::try_from(exp_year).change_context(
- errors::ApiErrorResponse::PreconditionFailed {
- message: "Invalid Expiry Year".to_string(),
- },
- )?;
+ let year = ::cards::CardExpirationYear::try_from(exp_year).change_context(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message: "Invalid Expiry Year".to_string(),
+ },
+ )?;
- let card_expiration = ::cards::CardExpiration { month, year };
- let is_expired = card_expiration.is_expired().change_context(
- errors::ApiErrorResponse::PreconditionFailed {
- message: "Invalid card data".to_string(),
- },
- )?;
- if is_expired {
- Err(report!(errors::ApiErrorResponse::PreconditionFailed {
- message: "Card Expired".to_string()
- }))?
- }
+ let card_expiration = ::cards::CardExpiration { month, year };
+ let is_expired = card_expiration.is_expired().change_context(
+ errors::ApiErrorResponse::PreconditionFailed {
+ message: "Invalid card data".to_string(),
+ },
+ )?;
+ if is_expired {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Card Expired".to_string()
+ }))?
}
+
Ok(())
}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index b2c8a3234a3..c6f6a23d0a2 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -648,6 +648,7 @@ pub async fn save_in_locker(
&card,
&customer_id,
merchant_account,
+ None,
)
.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 df6e24122a2..8280ddb6c2f 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -1,4 +1,4 @@
-use api_models::{enums, payouts};
+use api_models::{enums, payment_methods::Card, payouts};
use common_utils::{
errors::CustomResult,
ext_traits::{AsyncExt, StringExt},
@@ -14,9 +14,7 @@ use crate::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods::{
cards,
- transformers::{
- self, DataDuplicationCheck, StoreCardReq, StoreGenericReq, StoreLockerReq,
- },
+ transformers::{DataDuplicationCheck, StoreCardReq, StoreGenericReq, StoreLockerReq},
vault,
},
payments::{
@@ -212,7 +210,7 @@ pub async fn save_payout_data_to_locker(
let payload = StoreLockerReq::LockerCard(StoreCardReq {
merchant_id: merchant_account.merchant_id.as_ref(),
merchant_customer_id: payout_attempt.customer_id.to_owned(),
- card: transformers::Card {
+ card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.expiry_month.to_owned(),
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 74bb8bbc242..0b291855aa4 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -775,9 +775,12 @@ impl PaymentMethods {
.service(
web::resource("/{payment_method_id}")
.route(web::get().to(payment_method_retrieve_api))
- .route(web::post().to(payment_method_update_api))
.route(web::delete().to(payment_method_delete_api)),
)
+ .service(
+ web::resource("/{payment_method_id}/update")
+ .route(web::post().to(payment_method_update_api)),
+ )
.service(
web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)),
)
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 6c3d51f6592..a5ffcdabe33 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -219,22 +219,28 @@ pub async fn payment_method_update_api(
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
+ let payload = json_payload.into_inner();
+
+ let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ };
Box::pin(api::server_wrap(
flow,
state,
&req,
- json_payload.into_inner(),
- |state, auth, payload, _| {
+ payload,
+ |state, auth, req, _| {
cards::update_customer_payment_method(
state,
auth.merchant_account,
- payload,
+ req,
&payment_method_id,
auth.key_store,
)
},
- &auth::ApiKeyAuth,
+ &*auth,
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 748b6753f56..b04d3f3b6f6 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -862,6 +862,12 @@ impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest {
}
}
+impl ClientSecretFetch for api_models::payment_methods::PaymentMethodUpdate {
+ fn get_client_secret(&self) -> Option<&String> {
+ self.client_secret.as_ref()
+ }
+}
+
pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>(
headers: &HeaderMap,
) -> RouterResult<(
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 57d14aa923a..449265c86bc 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6993,6 +6993,38 @@
}
}
},
+ "CardDetailUpdate": {
+ "type": "object",
+ "required": [
+ "card_exp_month",
+ "card_exp_year",
+ "card_holder_name"
+ ],
+ "properties": {
+ "card_exp_month": {
+ "type": "string",
+ "description": "Card Expiry Month",
+ "example": "10"
+ },
+ "card_exp_year": {
+ "type": "string",
+ "description": "Card Expiry Year",
+ "example": "25"
+ },
+ "card_holder_name": {
+ "type": "string",
+ "description": "Card Holder Name",
+ "example": "John Doe"
+ },
+ "nick_name": {
+ "type": "string",
+ "description": "Card Holder's Nick Name",
+ "example": "John Doe",
+ "nullable": true
+ }
+ },
+ "additionalProperties": false
+ },
"CardNetwork": {
"type": "string",
"description": "Indicates the card network.",
@@ -12898,7 +12930,7 @@
"card": {
"allOf": [
{
- "$ref": "#/components/schemas/CardDetail"
+ "$ref": "#/components/schemas/CardDetailUpdate"
}
],
"nullable": true
@@ -12931,6 +12963,14 @@
"type": "object",
"description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",
"nullable": true
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK",
+ "example": "secret_k2uj3he2893eiu2d",
+ "nullable": true,
+ "maxLength": 30,
+ "minLength": 30
}
},
"additionalProperties": false
|
2024-04-04T13:56:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
`/payment_methods/update` endpoint doesn't currently perform the expected functionality. This PR revamps the endpoint such that
- Move update endpoint to `/payment_methods/:id/update`
- Verify whether update is necessary by comparing request fields with existing fields.
- If required, delete the existing payment method from locker.
- Create a new updated payment method and store it in locker
- Update the existing payment methods entry in Hyperswitch
Added card expiry validation during payment_methods endpoint (create and update).
This PR also moves `Card` object which represents the locker card object from router to api_models 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)?
-->
1. Create a customer
```
curl --location 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data-raw '{
"email": "guest@example.com",
"name": "new_cus",
"phone": "999999999",
"phone_country_code": "+65",
"description": "First customer",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
2. Create a payment method (use `/payment_methods` endpoint)
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "40",
"card_holder_name": "John"
},
"customer_id": "cus_a05bSJXwCoO01KZmWOdX",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

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

4. Do `list_payment_methods_for_customers` and verify whether updation of metadata is successful.
## Checklist
<!-- Put an `x` in 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
|
1b7cde2d1b687e9c5ca8e3c02eef5c7d3fb7da8f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4343
|
Bug: [FEATURE] Allow creation of mandates using payment_token
### Feature Description
Allow creation of mandates using payment_token, with setup_future_usage and customer_acceptance
### Possible Implementation
Decide based on mandate_type if the intention is to Make a recurring mandate with payment_token or to make a new mandate with payment_token
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index 704b7ae99f5..c15969fd1c8 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -1,3 +1,4 @@
+use api_models::payments as api_payments;
use common_enums::enums;
use common_utils::errors::CustomResult;
use data_models::mandates::MandateData;
@@ -7,7 +8,7 @@ use error_stack::ResultExt;
use crate::{
core::{errors, payments},
routes::AppState,
- types::domain,
+ types::{api, domain},
};
pub async fn get_profile_id_for_mandate(
@@ -40,6 +41,40 @@ pub async fn get_profile_id_for_mandate(
Ok(profile_id)
}
+pub fn get_mandate_type(
+ mandate_data: Option<api_payments::MandateData>,
+ off_session: Option<bool>,
+ setup_future_usage: Option<enums::FutureUsage>,
+ customer_acceptance: Option<api_payments::CustomerAcceptance>,
+ token: Option<String>,
+) -> CustomResult<Option<api::MandateTransactionType>, errors::ValidationError> {
+ match (
+ mandate_data.clone(),
+ off_session,
+ setup_future_usage,
+ customer_acceptance.or(mandate_data.and_then(|m_data| m_data.customer_acceptance)),
+ token,
+ ) {
+ (Some(_), Some(_), Some(enums::FutureUsage::OffSession), Some(_), Some(_)) => {
+ Err(errors::ValidationError::InvalidValue {
+ message: "Expected one out of recurring_details and mandate_data but got both"
+ .to_string(),
+ }
+ .into())
+ }
+ (_, _, Some(enums::FutureUsage::OffSession), Some(_), Some(_))
+ | (_, _, Some(enums::FutureUsage::OffSession), Some(_), _)
+ | (Some(_), _, Some(enums::FutureUsage::OffSession), _, _) => {
+ Ok(Some(api::MandateTransactionType::NewMandateTransaction))
+ }
+
+ (_, _, Some(enums::FutureUsage::OffSession), _, Some(_)) | (_, Some(_), _, _, _) => Ok(
+ Some(api::MandateTransactionType::RecurringMandateTransaction),
+ ),
+
+ _ => Ok(None),
+ }
+}
#[derive(Clone)]
pub struct MandateGenericData {
pub token: Option<String>,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e74a8c1d1ec..d56c4cfea5d 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -129,13 +129,13 @@ where
customer_details,
mut payment_data,
business_profile,
+ mandate_type,
} = operation
.to_get_tracker()?
.get_trackers(
state,
&validate_result.payment_id,
&req,
- validate_result.mandate_type.to_owned(),
&merchant_account,
&key_store,
auth_flow,
@@ -166,6 +166,7 @@ where
&key_store,
&mut payment_data,
eligible_connectors,
+ mandate_type,
)
.await?;
@@ -2655,6 +2656,7 @@ pub async fn get_connector_choice<F, Req, Ctx>(
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<Option<ConnectorCallType>>
where
F: Send + Clone,
@@ -2694,6 +2696,7 @@ where
payment_data,
Some(straight_through),
eligible_connectors,
+ mandate_type,
)
.await?
}
@@ -2707,6 +2710,7 @@ where
payment_data,
None,
eligible_connectors,
+ mandate_type,
)
.await?
}
@@ -2723,6 +2727,7 @@ where
Ok(connector)
}
+#[allow(clippy::too_many_arguments)]
pub async fn connector_selection<F>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
@@ -2731,6 +2736,7 @@ pub async fn connector_selection<F>(
payment_data: &mut PaymentData<F>,
request_straight_through: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
@@ -2772,6 +2778,7 @@ where
request_straight_through,
&mut routing_data,
eligible_connectors,
+ mandate_type,
)
.await?;
@@ -2805,6 +2812,7 @@ pub async fn decide_connector<F>(
request_straight_through: Option<api::routing::StraightThroughAlgorithm>,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
@@ -2936,6 +2944,7 @@ where
payment_data,
routing_data,
connector_data,
+ mandate_type,
)
.await;
}
@@ -2992,6 +3001,7 @@ where
payment_data,
routing_data,
connector_data,
+ mandate_type,
)
.await;
}
@@ -3004,6 +3014,7 @@ where
TransactionData::Payment(payment_data),
routing_data,
eligible_connectors,
+ mandate_type,
)
.await
}
@@ -3013,16 +3024,30 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone
payment_data: &mut PaymentData<F>,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorData>,
+ mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType> {
match (
payment_data.payment_intent.setup_future_usage,
payment_data.token_data.as_ref(),
payment_data.recurring_details.as_ref(),
payment_data.payment_intent.off_session,
+ mandate_type,
) {
- (Some(storage_enums::FutureUsage::OffSession), Some(_), None, None)
- | (None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true))
- | (None, Some(_), None, Some(true)) => {
+ (
+ Some(storage_enums::FutureUsage::OffSession),
+ Some(_),
+ None,
+ None,
+ Some(api::MandateTransactionType::RecurringMandateTransaction),
+ )
+ | (
+ None,
+ None,
+ Some(RecurringDetails::PaymentMethodId(_)),
+ Some(true),
+ Some(api::MandateTransactionType::RecurringMandateTransaction),
+ )
+ | (None, Some(_), None, Some(true), _) => {
logger::debug!("performing routing for token-based MIT flow");
let payment_method_info = payment_data
@@ -3326,6 +3351,7 @@ where
Ok(final_list)
}
+#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v1<F>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
@@ -3334,6 +3360,7 @@ pub async fn route_connector_v1<F>(
transaction_data: TransactionData<'_, F>,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
+ mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
@@ -3424,6 +3451,7 @@ where
payment_data,
routing_data,
connector_data,
+ mandate_type,
)
.await
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index f8aa463a44b..de74abe8603 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -430,7 +430,7 @@ pub async fn get_token_pm_type_mandate_details(
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
- Some(mandate_data.clone().get_required_value("mandate_data")?),
+ mandate_data.clone(),
None,
None,
None,
@@ -493,29 +493,37 @@ pub async fn get_token_pm_type_mandate_details(
}
},
None => {
- let mandate_id = request
- .mandate_id
- .clone()
- .get_required_value("mandate_id")?;
- let mandate_generic_data = get_token_for_recurring_mandate(
- state,
- request,
- merchant_account,
- merchant_key_store,
- mandate_id,
- )
- .await?;
- (
- mandate_generic_data.token,
- mandate_generic_data.payment_method,
- mandate_generic_data
- .payment_method_type
- .or(request.payment_method_type),
- None,
- mandate_generic_data.recurring_mandate_payment_data,
- mandate_generic_data.mandate_connector,
- None,
- )
+ if let Some(mandate_id) = request.mandate_id.clone() {
+ let mandate_generic_data = get_token_for_recurring_mandate(
+ state,
+ request,
+ merchant_account,
+ merchant_key_store,
+ mandate_id,
+ )
+ .await?;
+ (
+ mandate_generic_data.token,
+ mandate_generic_data.payment_method,
+ mandate_generic_data
+ .payment_method_type
+ .or(request.payment_method_type),
+ None,
+ mandate_generic_data.recurring_mandate_payment_data,
+ mandate_generic_data.mandate_connector,
+ None,
+ )
+ } else {
+ (
+ request.payment_token.to_owned(),
+ request.payment_method,
+ request.payment_method_type,
+ None,
+ None,
+ None,
+ None,
+ )
+ }
}
}
}
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index cad02fc7210..44256b6a718 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -79,7 +79,6 @@ pub trait Operation<F: Clone, T, Ctx: PaymentMethodRetrieve>: Send + std::fmt::D
pub struct ValidateResult<'a> {
pub merchant_id: &'a str,
pub payment_id: api::PaymentIdType,
- pub mandate_type: Option<api::MandateTransactionType>,
pub storage_scheme: enums::MerchantStorageScheme,
pub requeue: bool,
}
@@ -98,6 +97,7 @@ pub struct GetTrackerResponse<'a, F: Clone, R, Ctx> {
pub customer_details: Option<CustomerDetails>,
pub payment_data: PaymentData<F>,
pub business_profile: storage::business_profile::BusinessProfile,
+ pub mandate_type: Option<api::MandateTransactionType>,
}
#[async_trait]
@@ -108,7 +108,6 @@ pub trait GetTracker<F: Clone, D, R, Ctx: PaymentMethodRetrieve>: Send {
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &R,
- mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
mechant_key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index e25ef7ed4a4..b47608eba98 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -38,7 +38,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsCaptureRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -186,6 +185,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: None,
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -259,7 +259,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
request.payment_id.clone(),
"payment_id",
)?),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index ab5feb5d9b5..9cd9ba9f6d4 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -39,7 +39,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCancelRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -195,6 +194,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: None,
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -281,7 +281,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 4445589f42f..c6dfe6bd3cb 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -38,7 +38,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCaptureRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -239,6 +238,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: None,
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -313,7 +313,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
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 e1a16b6f4a2..413a4b03895 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -10,7 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- mandate::helpers::MandateGenericData,
+ mandate::helpers as m_helpers,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
@@ -40,7 +40,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
- mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -72,23 +71,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"confirm",
)?;
- let MandateGenericData {
- token,
- payment_method,
- payment_method_type,
- mandate_data,
- recurring_mandate_payment_data,
- mandate_connector,
- payment_method_info,
- } = helpers::get_token_pm_type_mandate_details(
- state,
- request,
- mandate_type.to_owned(),
- merchant_account,
- key_store,
- )
- .await?;
-
let browser_info = request
.browser_info
.clone()
@@ -99,6 +81,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
field_name: "browser_info",
})?;
+ let recurring_details = request.recurring_details.clone();
+ let customer_acceptance = request.customer_acceptance.clone().map(From::from);
+
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
@@ -109,6 +94,33 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let mandate_type = m_helpers::get_mandate_type(
+ request.mandate_data.clone(),
+ request.off_session,
+ payment_intent.setup_future_usage,
+ request.customer_acceptance.clone(),
+ request.payment_token.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::MandateValidationFailed {
+ reason: "Expected one out of recurring_details and mandate_data but got both".into(),
+ })?;
+
+ let m_helpers::MandateGenericData {
+ token,
+ payment_method,
+ payment_method_type,
+ mandate_data,
+ recurring_mandate_payment_data,
+ mandate_connector,
+ payment_method_info,
+ } = helpers::get_token_pm_type_mandate_details(
+ state,
+ request,
+ mandate_type.to_owned(),
+ merchant_account,
+ key_store,
+ )
+ .await?;
let token = token.or_else(|| payment_attempt.payment_token.clone());
if let Some(payment_method) = payment_method {
@@ -259,7 +271,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_id: None,
mandate_connector,
setup_mandate,
- customer_acceptance: None,
+ customer_acceptance,
token,
token_data,
address: PaymentAddress::new(
@@ -293,7 +305,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: None,
- recurring_details: request.recurring_details.clone(),
+ recurring_details,
};
let customer_details = Some(CustomerDetails {
@@ -309,6 +321,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details,
payment_data,
business_profile,
+ mandate_type,
};
Ok(get_trackers_response)
@@ -456,7 +469,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
- let mandate_type =
+ let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
@@ -470,7 +483,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?,
- mandate_type,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
request.retry_action,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 8e66f436817..458e05fd2e9 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -15,7 +15,7 @@ use crate::{
authentication,
blocklist::utils as blocklist_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- mandate::helpers::MandateGenericData,
+ mandate::helpers as m_helpers,
payment_methods::PaymentMethodRetrieve,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
@@ -47,7 +47,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
- mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
@@ -62,47 +61,18 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
// Stage 1
- let store = state.clone().store;
+ let store = &*state.store;
let m_merchant_id = merchant_id.clone();
- let payment_intent_fut = tokio::spawn(
- async move {
- store
- .find_payment_intent_by_payment_id_merchant_id(
- &payment_id,
- m_merchant_id.as_str(),
- storage_scheme,
- )
- .map(|x| x.change_context(errors::ApiErrorResponse::PaymentNotFound))
- .await
- }
- .in_current_span(),
- );
-
- let m_state = state.clone();
- let m_mandate_type = mandate_type.clone();
- let m_merchant_account = merchant_account.clone();
- let m_request = request.clone();
- let m_key_store = key_store.clone();
-
- let mandate_details_fut = tokio::spawn(
- async move {
- helpers::get_token_pm_type_mandate_details(
- &m_state,
- &m_request,
- m_mandate_type,
- &m_merchant_account,
- &m_key_store,
- )
- .await
- }
- .in_current_span(),
- );
// Parallel calls - level 0
- let (mut payment_intent, mandate_details) = tokio::try_join!(
- utils::flatten_join_error(payment_intent_fut),
- utils::flatten_join_error(mandate_details_fut)
- )?;
+ let mut payment_intent = store
+ .find_payment_intent_by_payment_id_merchant_id(
+ &payment_id,
+ m_merchant_id.as_str(),
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
@@ -352,16 +322,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.setup_future_usage
.or(payment_intent.setup_future_usage);
- let MandateGenericData {
- token,
- payment_method,
- payment_method_type,
- mandate_data,
- recurring_mandate_payment_data,
- mandate_connector,
- payment_method_info,
- } = mandate_details;
-
let browser_info = request
.browser_info
.clone()
@@ -374,6 +334,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
})?;
let customer_acceptance = request.customer_acceptance.clone().map(From::from);
+ let recurring_details = request.recurring_details.clone();
+
helpers::validate_card_data(
request
.payment_method_data
@@ -381,46 +343,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.map(|pmd| pmd.payment_method_data.clone()),
)?;
- let token = token.or_else(|| payment_attempt.payment_token.clone());
-
- helpers::validate_pm_or_token_given(
- &request.payment_method,
- &request
- .payment_method_data
- .as_ref()
- .map(|pmd| pmd.payment_method_data.clone()),
- &request.payment_method_type,
- &mandate_type,
- &token,
- )?;
-
- let (token_data, payment_method_info) = if let Some(token) = token.clone() {
- let token_data = helpers::retrieve_payment_token_data(
- state,
- token,
- payment_method.or(payment_attempt.payment_method),
- )
- .await?;
-
- let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(
- state,
- &token_data,
- storage_scheme,
- )
- .await?;
-
- (Some(token_data), payment_method_info)
- } else {
- (None, payment_method_info)
- };
-
- payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info;
- payment_attempt.payment_method_type = payment_method_type
- .or(payment_attempt.payment_method_type)
- .or(payment_method_info
- .as_ref()
- .and_then(|pm_info| pm_info.payment_method_type));
payment_attempt.payment_experience = request
.payment_experience
@@ -485,23 +408,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.clone()
.or(payment_attempt.business_sub_label);
- // The operation merges mandate data from both request and payment_attempt
- let setup_mandate = mandate_data.map(|mut sm| {
- sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
- sm.update_mandate_id = payment_attempt
- .mandate_data
- .clone()
- .and_then(|mandate| mandate.update_mandate_id)
- .or(sm.update_mandate_id);
- sm
- });
-
- let mandate_details_present =
- payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
- helpers::validate_mandate_data_and_future_usage(
- payment_intent.setup_future_usage,
- mandate_details_present,
- )?;
let n_request_payment_method_data = request
.payment_method_data
.as_ref()
@@ -553,13 +459,112 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
.in_current_span(),
);
+ let mandate_type = m_helpers::get_mandate_type(
+ request.mandate_data.clone(),
+ request.off_session,
+ payment_intent.setup_future_usage,
+ request.customer_acceptance.clone(),
+ request.payment_token.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::MandateValidationFailed {
+ reason: "Expected one out of recurring_details and mandate_data but got both".into(),
+ })?;
+
+ let m_state = state.clone();
+ let m_mandate_type = mandate_type.clone();
+ let m_merchant_account = merchant_account.clone();
+ let m_request = request.clone();
+ let m_key_store = key_store.clone();
+
+ let mandate_details_fut = tokio::spawn(
+ async move {
+ helpers::get_token_pm_type_mandate_details(
+ &m_state,
+ &m_request,
+ m_mandate_type,
+ &m_merchant_account,
+ &m_key_store,
+ )
+ .await
+ }
+ .in_current_span(),
+ );
// Parallel calls - level 2
- let (additional_pm_data, payment_method_billing) = tokio::try_join!(
+ let (mandate_details, additional_pm_data, payment_method_billing) = tokio::try_join!(
+ utils::flatten_join_error(mandate_details_fut),
utils::flatten_join_error(additional_pm_data_fut),
utils::flatten_join_error(payment_method_billing_future),
)?;
+ let m_helpers::MandateGenericData {
+ token,
+ payment_method,
+ payment_method_type,
+ mandate_data,
+ recurring_mandate_payment_data,
+ mandate_connector,
+ payment_method_info,
+ } = mandate_details;
+
+ 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)
+ .or(payment_method_info
+ .as_ref()
+ .and_then(|pm_info| pm_info.payment_method_type));
+
+ let token = token.or_else(|| payment_attempt.payment_token.clone());
+
+ helpers::validate_pm_or_token_given(
+ &request.payment_method,
+ &request
+ .payment_method_data
+ .as_ref()
+ .map(|pmd| pmd.payment_method_data.clone()),
+ &request.payment_method_type,
+ &mandate_type,
+ &token,
+ )?;
+
+ let (token_data, payment_method_info) = if let Some(token) = token.clone() {
+ let token_data = helpers::retrieve_payment_token_data(
+ state,
+ token,
+ payment_method.or(payment_attempt.payment_method),
+ )
+ .await?;
+
+ let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(
+ state,
+ &token_data,
+ storage_scheme,
+ )
+ .await?;
+
+ (Some(token_data), payment_method_info)
+ } else {
+ (None, payment_method_info)
+ };
+ // The operation merges mandate data from both request and payment_attempt
+ let setup_mandate = mandate_data.map(|mut sm| {
+ sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
+ sm.update_mandate_id = payment_attempt
+ .mandate_data
+ .clone()
+ .and_then(|mandate| mandate.update_mandate_id)
+ .or(sm.update_mandate_id);
+ sm
+ });
+
+ let mandate_details_present =
+ payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
+ helpers::validate_mandate_data_and_future_usage(
+ payment_intent.setup_future_usage,
+ mandate_details_present,
+ )?;
+
let payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
@@ -627,7 +632,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
frm_metadata: request.frm_metadata.clone(),
authentication,
- recurring_details: request.recurring_details.clone(),
+ recurring_details,
};
let get_trackers_response = operations::GetTrackerResponse {
@@ -635,6 +640,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: Some(customer_details),
payment_data,
business_profile,
+ mandate_type,
};
Ok(get_trackers_response)
@@ -1212,7 +1218,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
- let mandate_type =
+ let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
@@ -1231,7 +1237,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?,
- mandate_type,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
request.retry_action,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index c6e95b176c1..944580c4f08 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -21,7 +21,7 @@ use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- mandate::helpers::MandateGenericData,
+ mandate::helpers as m_helpers,
payment_link,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
@@ -58,7 +58,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
- mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -106,8 +105,22 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
id: profile_id.to_string(),
})?
};
+ let customer_acceptance = request.customer_acceptance.clone().map(From::from);
+
+ let recurring_details = request.recurring_details.clone();
+
+ let mandate_type = m_helpers::get_mandate_type(
+ request.mandate_data.clone(),
+ request.off_session,
+ request.setup_future_usage,
+ request.customer_acceptance.clone(),
+ request.payment_token.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::MandateValidationFailed {
+ reason: "Expected one out of recurring_details and mandate_data but got both".into(),
+ })?;
- let MandateGenericData {
+ let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
@@ -118,7 +131,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
} = helpers::get_token_pm_type_mandate_details(
state,
request,
- mandate_type,
+ mandate_type.clone(),
merchant_account,
merchant_key_store,
)
@@ -375,8 +388,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data.map(MandateData::from);
- let customer_acceptance = request.customer_acceptance.clone().map(From::from);
-
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
@@ -434,7 +445,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: request.frm_metadata.clone(),
- recurring_details: request.recurring_details.clone(),
+ recurring_details,
};
let get_trackers_response = operations::GetTrackerResponse {
@@ -442,6 +453,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: Some(customer_details),
payment_data,
business_profile,
+ mandate_type,
};
Ok(get_trackers_response)
@@ -726,7 +738,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id,
- mandate_type,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
request.retry_action,
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index e1d58b032aa..506f372e947 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -37,7 +37,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
_request: &PaymentsCancelRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -182,6 +181,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: None,
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -273,7 +273,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsCan
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 25b419e3222..19075759ef1 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -39,7 +39,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsSessionRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -207,6 +206,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: Some(customer_details),
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -276,7 +276,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 560d2014bae..9a952f0a526 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -38,7 +38,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsStartRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -194,6 +193,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: Some(customer_details),
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -252,7 +252,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 6739c2c3ba7..5335c273b6e 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -206,7 +206,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRetrieveRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -494,6 +493,7 @@ async fn get_tracker_for_sync<
customer_details: None,
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -522,7 +522,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: request.resource_id.clone(),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 934c0edfddd..fce8bd0f0be 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -13,7 +13,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- mandate::helpers::MandateGenericData,
+ mandate::helpers as m_helpers,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
@@ -43,7 +43,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
- mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
@@ -98,23 +97,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
- let MandateGenericData {
- token,
- payment_method,
- payment_method_type,
- mandate_data,
- recurring_mandate_payment_data,
- mandate_connector,
- payment_method_info,
- } = helpers::get_token_pm_type_mandate_details(
- state,
- request,
- mandate_type.to_owned(),
- merchant_account,
- key_store,
- )
- .await?;
-
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
@@ -136,6 +118,36 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let customer_acceptance = request.customer_acceptance.clone().map(From::from);
+ let recurring_details = request.recurring_details.clone();
+
+ let mandate_type = m_helpers::get_mandate_type(
+ request.mandate_data.clone(),
+ request.off_session,
+ payment_intent.setup_future_usage,
+ request.customer_acceptance.clone(),
+ request.payment_token.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::MandateValidationFailed {
+ reason: "Expected one out of recurring_details and mandate_data but got both".into(),
+ })?;
+
+ let m_helpers::MandateGenericData {
+ token,
+ payment_method,
+ payment_method_type,
+ mandate_data,
+ recurring_mandate_payment_data,
+ mandate_connector,
+ payment_method_info,
+ } = helpers::get_token_pm_type_mandate_details(
+ state,
+ request,
+ mandate_type.to_owned(),
+ merchant_account,
+ key_store,
+ )
+ .await?;
helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;
helpers::validate_request_amount_and_amount_to_capture(
@@ -390,7 +402,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
id: profile_id.to_string(),
})?;
- let customer_acceptance = request.customer_acceptance.clone().map(From::from);
+
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
@@ -439,7 +451,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: request.frm_metadata.clone(),
- recurring_details: request.recurring_details.clone(),
+ recurring_details,
};
let get_trackers_response = operations::GetTrackerResponse {
@@ -447,6 +459,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: Some(customer_details),
payment_data,
business_profile,
+ mandate_type,
};
Ok(get_trackers_response)
@@ -750,7 +763,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
- let mandate_type = helpers::validate_mandate(request, false)?;
+ let _mandate_type = helpers::validate_mandate(request, false)?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
@@ -763,7 +776,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?,
- mandate_type,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
request.retry_action,
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index be2b127ff67..e453ec0106d 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -42,7 +42,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
state: &'a AppState,
payment_id: &api::PaymentIdType,
request: &PaymentsIncrementalAuthorizationRequest,
- _mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
@@ -160,6 +159,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
customer_details: None,
payment_data,
business_profile,
+ mandate_type: None,
};
Ok(get_trackers_response)
@@ -275,7 +275,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
operations::ValidateResult {
merchant_id: &merchant_account.merchant_id,
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
- mandate_type: None,
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index ef54cedcb8d..34e121bd337 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -778,6 +778,7 @@ pub async fn decide_payout_connector(
TransactionData::<()>::Payout(payout_data),
routing_data,
eligible_connectors,
+ None,
)
.await
}
|
2024-04-10T16:55:55Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR supports creating a mandate by passing `payment_token` with , `setup_future_usage:off_session` and `customer_acceptance`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create an MA and MCA
- `Step 1:`Make a save card payment
- `Step 2:` List Customer Payment Method, get the `payment_token`
- `Step 3:` Use the `payment token` to create the mandate
> Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1ORGV1egb2qN8z8UoZE7pCkv7cUMiXbdMwZYZJNX8qjm2aTW9uAcX2d3ezX4g3KY' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c77",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>Confirm
```
curl --location 'http://localhost:8080/payments/pay_up5SZAykikpNXZqLivDP/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1ORGV1egb2qN8z8UoZE7pCkv7cUMiXbdMwZYZJNX8qjm2aTW9uAcX2d3ezX4g3KY' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_token": "{{payment_token}}",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}}
}'
```
- `Step4:` Do a recurring payment, with `off_session:true`
>Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1ORGV1egb2qN8z8UoZE7pCkv7cUMiXbdMwZYZJNX8qjm2aTW9uAcX2d3ezX4g3KY' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": true,
"customer_id": "new-c77",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"off_session": true,
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"recurring_details":{
"type":"payment_method_id",
"data":"{{payment_method_id}}"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
-> UseCase 2 (for doing a recurring payment with `setup_future_usage:off_session`):
- Create an MA and MCA with cybersource
- Follow the above steps From 1 - 3
- Do a List Customer PaymentMethods to get the token
- Do a recurring_payment with `payment_token + setup_future_usage:off_session` and no `customer_acceptance`
>Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_EDXOKcN5iMxjonvVaA0bjl2Qn37J15SxoQ6QX3QFHEgA8P1HGj9CLj4sClVM9dB4' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c77",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>Confirm
```
curl --location 'http://localhost:8080/payments/pay_DpS8eVBQRvmlHIvWPrJK/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_EDXOKcN5iMxjonvVaA0bjl2Qn37J15SxoQ6QX3QFHEgA8P1HGj9CLj4sClVM9dB4' \
--data '{
"confirm": true,
"payment_token": "{{payment_token}}"
}'
```
## Checklist
<!-- Put 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
|
2bf775a97e331cde2cad3e3d2a325850d969add9
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4302
|
Bug: remove mget from redis interface
|
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index 21630fc3c08..d9b7072ff8c 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -306,45 +306,6 @@ impl super::RedisConnectionPool {
.await
}
- #[instrument(level = "DEBUG", skip(self))]
- pub async fn get_multiple_keys<K, V>(
- &self,
- keys: K,
- ) -> CustomResult<Vec<Option<V>>, errors::RedisError>
- where
- V: FromRedis + Unpin + Send + 'static,
- K: Into<MultipleKeys> + Send + Debug,
- {
- self.pool
- .mget(keys)
- .await
- .change_context(errors::RedisError::GetFailed)
- }
-
- #[instrument(level = "DEBUG", skip(self))]
- pub async fn get_and_deserialize_multiple_keys<K, V>(
- &self,
- keys: K,
- type_name: &'static str,
- ) -> CustomResult<Vec<Option<V>>, errors::RedisError>
- where
- K: Into<MultipleKeys> + Send + Debug,
- V: serde::de::DeserializeOwned,
- {
- let data = self.get_multiple_keys::<K, Vec<u8>>(keys).await?;
- data.into_iter()
- .map(|value_bytes| {
- value_bytes
- .map(|bytes| {
- bytes
- .parse_struct(type_name)
- .change_context(errors::RedisError::JsonSerializationFailed)
- })
- .transpose()
- })
- .collect()
- }
-
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>(
&self,
|
2024-04-04T12:16:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Getting multiple values from Redis at one time was working fine in local environment but was failing when deployed because of mutiple clusters at infra level.
### 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 #4302
## How did you test it?
#3945 when deployed, caused sandbox to fail.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
63d2b6855acee1adeae2efff10f424e056af0bcb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4299
|
Bug: [REFACTOR] : [Stripe] Add support for recurring payments for GooglePay
### Feature Description
Add support for recurring payments for GooglePay
### Have you spent some time to check if this feature request has been raised before?
- [X] I checked and didn't find similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
yes
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 45aeb1e9074..211ac559fec 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -637,10 +637,11 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
enums::PaymentMethodType::Blik => Ok(Self::Blik),
enums::PaymentMethodType::AliPay => Ok(Self::Alipay),
enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24),
+ // Stripe expects PMT as Card for Recurring Mandates Payments
+ enums::PaymentMethodType::GooglePay => Ok(Self::Card),
enums::PaymentMethodType::Boleto
| enums::PaymentMethodType::CardRedirect
| enums::PaymentMethodType::CryptoCurrency
- | enums::PaymentMethodType::GooglePay
| enums::PaymentMethodType::Multibanco
| enums::PaymentMethodType::OnlineBankingFpx
| enums::PaymentMethodType::Paypal
|
2024-04-04T11:14:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add Support for Google Pay recurring Payments for Stripe Connector
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
TESTING WITH `PAYMENT_METHOD_ID`
1. Create a CIT Gpay Payment vai Stripe
```
{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_data": {
"wallet": {
"google_pay": {
"type": "CARD",
"description": "Visa •••• 1111",
"info": {
"card_network": "VISA",
"card_details": "1111"
},
"tokenization_data": {
"type": "PAYMENT_GATEWAY",
"token": "{token}"
}
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"setup_future_usage":"off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}
```
Response
```
{
"payment_id": "pay_Silkngki34Xj28mT1R1R",
"merchant_id": "postman_merchant_GHAction_0c456d29-8ea8-46c4-b7d3-505b40939a33",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_Silkngki34Xj28mT1R1R_secret_8mOW2gVLoDXXapxWgEuL",
"created": "2024-04-04T10:46:16.907Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1712227576,
"expires": 1712231176,
"secret": "epk_91696cceeba74e73b4fef04e3c8a53f1"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3P1noDD5R7gDAGff0v863vps",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1noDD5R7gDAGff0v863vps",
"payment_link": null,
"profile_id": "pro_4Aycmjy6kMC33pEisLdF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_vNxTuQF8uaucUyRapDoP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-04T11:01:16.907Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_j3BWlKSBMuA9EtL3tf57",
"payment_method_status": null
}
```
2. hit List Payment methods for a Customer
Response:
```
{
"customer_payment_methods": [
{
"payment_token": "token_C4qwVJSMzYaFroUCpVeZ",
"payment_method_id": "pm_j3BWlKSBMuA9EtL3tf57",
"customer_id": "StripeCustomer",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-04-04T10:46:18.816Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-04-04T10:46:18.816Z",
"default_payment_method_set": false
},
{
"payment_token": "token_aDMvZRRb5KS1kxgxduvj",
"payment_method_id": "pm_wG1aHDa0PGZ5Wa64HL30",
"customer_id": "StripeCustomer",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-04-04T10:42:12.538Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-04-04T10:42:12.538Z",
"default_payment_method_set": false
},
{
"payment_token": "token_pahJKG3OsrkDDGEMC7M5",
"payment_method_id": "pm_Y8E7W5doyuL44l67EDdV",
"customer_id": "StripeCustomer",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "25",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-04-04T10:17:39.092Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-04-04T10:17:39.092Z",
"default_payment_method_set": false
},
{
"payment_token": "token_BeNSN078uVSljFekB3V2",
"payment_method_id": "pm_BvBX5hIT5sCQrR3b4PLL",
"customer_id": "StripeCustomer",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-04-04T10:14:45.411Z",
"`bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-04-04T10:14:45.411Z",
"default_payment_method_set": true
}
],
"is_guest_customer": null
}
```
In Response we will get `payment_method_id` .
3. Using this `payment_method_id` we will create MIT
Request:
```
{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"off_session": true,
"recurring_details":{
"type":"payment_method_id",
"data":"pm_j3BWlKSBMuA9EtL3tf57"
}
}
```
Response:
```
{
"payment_id": "pay_qYkH7UxBL4FX9vu0PRRD",
"merchant_id": "postman_merchant_GHAction_0c456d29-8ea8-46c4-b7d3-505b40939a33",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_qYkH7UxBL4FX9vu0PRRD_secret_E7VCnAywLHOH3lkMrElM",
"created": "2024-04-04T10:46:43.831Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1712227603,
"expires": 1712231203,
"secret": "epk_90826711922c44269fbbb248ec758e87"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3P1noeD5R7gDAGff06hbQBvc",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1noeD5R7gDAGff06hbQBvc",
"payment_link": null,
"profile_id": "pro_4Aycmjy6kMC33pEisLdF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_vNxTuQF8uaucUyRapDoP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-04T11:01:43.831Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_j3BWlKSBMuA9EtL3tf57",
"payment_method_status": "active"
}
```
________________________________________________
TESTING WITH `MANDATE_ID`
1. Create a CIT GPay Payment vai Stripe
```
{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_data": {
"wallet": {
"google_pay": {
"type": "CARD",
"description": "Visa •••• 1111",
"info": {
"card_network": "VISA",
"card_details": "1111"
},
"tokenization_data": {
"type": "PAYMENT_GATEWAY",
"token": "{\n \"id\": \"tok_1P1oLhD5R7gDAGffwVji8BOz\",\n \"object\": \"token\",\n \"card\": {\n \"id\": \"card_1P1oLhD5R7gDAGffYyDUTBCD\",\n \"object\": \"card\",\n \"address_city\": null,\n \"address_country\": null,\n \"address_line1\": null,\n \"address_line1_check\": null,\n \"address_line2\": null,\n \"address_state\": null,\n \"address_zip\": null,\n \"address_zip_check\": null,\n \"brand\": \"Visa\",\n \"country\": \"US\",\n \"cvc_check\": null,\n \"dynamic_last4\": \"1111\",\n \"exp_month\": 12,\n \"exp_year\": 2026,\n \"funding\": \"credit\",\n \"last4\": \"1111\",\n \"metadata\": {},\n \"name\": null,\n \"networks\": {\n \"preferred\": null\n },\n \"tokenization_method\": \"android_pay\",\n \"wallet\": null\n },\n \"client_ip\": \"209.85.198.69\",\n \"created\": 1712229653,\n \"livemode\": false,\n \"type\": \"card\",\n \"used\": false\n}"
}
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"setup_future_usage":"off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 6540,
"currency": "USD"
}
}
}
}
```
Response:
```
{
"payment_id": "pay_CcnuFccKKipXJQPzJ74C",
"merchant_id": "postman_merchant_GHAction_0c456d29-8ea8-46c4-b7d3-505b40939a33",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_CcnuFccKKipXJQPzJ74C_secret_4cfaK4bXzSMj8OCBOWZ7",
"created": "2024-04-04T11:22:25.205Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": "man_Hm4KrSW3363qNgnZgd0o",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 6540,
"currency": "USD",
"start_date": null,
"end_date": null,
"metadata": null
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1712229745,
"expires": 1712233345,
"secret": "epk_740115c98bce48a5bbbfcb2b150c7bf6"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3P1oNBD5R7gDAGff0JAzGZOx",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1oNBD5R7gDAGff0JAzGZOx",
"payment_link": null,
"profile_id": "pro_4Aycmjy6kMC33pEisLdF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_vNxTuQF8uaucUyRapDoP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-04T11:37:25.205Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_BKkvrO0nVTq0xlUv57mL",
"payment_method_status": null
}
```
In response we get `mandate_id`
2. Using `mandate_id` create a MIT payment
```
{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"off_session": true,
"recurring_details":{
"type":"mandate_id",
"data":"man_Hm4KrSW3363qNgnZgd0o"
}
}
```
Response:
```
{
"payment_id": "pay_NQjh6W6gsMlMKuWOgj6p",
"merchant_id": "postman_merchant_GHAction_0c456d29-8ea8-46c4-b7d3-505b40939a33",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_NQjh6W6gsMlMKuWOgj6p_secret_auS1fIEZirRtoGcGKYU1",
"created": "2024-04-04T11:22:57.184Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": "man_Hm4KrSW3363qNgnZgd0o",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1712229777,
"expires": 1712233377,
"secret": "epk_4e626057208d4d82bc1d3b0abcce4a39"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3P1oNhD5R7gDAGff03J1Ljzq",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1oNhD5R7gDAGff03J1Ljzq",
"payment_link": null,
"profile_id": "pro_4Aycmjy6kMC33pEisLdF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_vNxTuQF8uaucUyRapDoP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-04T11:37:57.184Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
63d2b6855acee1adeae2efff10f424e056af0bcb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4297
|
Bug: feat: Add cookie parsing
Parse cookie header to get JWT. Compare with the JWT retrieved from `Authorization` header and log the result.
|
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 0181ec4e799..a7c54ef8f34 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -427,6 +427,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
| errors::ApiErrorResponse::InvalidJwtToken
| errors::ApiErrorResponse::GenericUnauthorized { .. }
| errors::ApiErrorResponse::AccessForbidden { .. }
+ | errors::ApiErrorResponse::InvalidCookie
| errors::ApiErrorResponse::InvalidEphemeralKey => Self::Unauthorized,
errors::ApiErrorResponse::InvalidRequestUrl
| errors::ApiErrorResponse::InvalidHttpMethod
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index b3fbbaaf141..dc3e19cb725 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -260,6 +260,11 @@ pub enum ApiErrorResponse {
CurrencyConversionFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_26",
+ message = "Invalid Cookie"
+ )]
+ InvalidCookie,
}
impl PTError for ApiErrorResponse {
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index 110feb22df3..7c06fc92c99 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -292,6 +292,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::PaymentMethodDeleteFailed => {
AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
}
+ Self::InvalidCookie => {
+ AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
+ }
}
}
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index d2247150d3c..f7acbe6f933 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -5,6 +5,7 @@ use common_utils::date_time;
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use masking::PeekInterface;
+use router_env::logger;
use serde::Serialize;
use self::blacklist::BlackList;
@@ -33,7 +34,6 @@ use crate::{
utils::OptionExt,
};
pub mod blacklist;
-#[cfg(feature = "olap")]
pub mod cookies;
#[derive(Clone, Debug)]
@@ -598,6 +598,15 @@ where
A: AppStateInfo + Sync,
{
let token = get_jwt_from_authorization_header(headers)?;
+ if let Some(token_from_cookies) = get_cookie_from_header(headers)
+ .ok()
+ .and_then(|cookies| cookies::parse_cookie(cookies).ok())
+ {
+ logger::info!(
+ "Cookie header and authorization header JWT comparison result: {}",
+ token == token_from_cookies
+ );
+ }
let payload = decode_jwt(token, state).await?;
Ok(payload)
@@ -959,6 +968,13 @@ pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&s
.ok_or(errors::ApiErrorResponse::InvalidJwtToken.into())
}
+pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> {
+ headers
+ .get(cookies::get_cookie_header())
+ .and_then(|header_value| header_value.to_str().ok())
+ .ok_or(errors::ApiErrorResponse::InvalidCookie.into())
+}
+
pub fn strip_jwt_token(token: &str) -> RouterResult<&str> {
token
.strip_prefix("Bearer ")
diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs
index d7fc4c10315..96518840800 100644
--- a/crates/router/src/services/authentication/cookies.rs
+++ b/crates/router/src/services/authentication/cookies.rs
@@ -1,15 +1,27 @@
+use cookie::Cookie;
+#[cfg(feature = "olap")]
use cookie::{
time::{Duration, OffsetDateTime},
- Cookie, SameSite,
+ SameSite,
};
-use masking::{ExposeInterface, Mask, Secret};
+use error_stack::{report, ResultExt};
+#[cfg(feature = "olap")]
+use masking::Mask;
+#[cfg(feature = "olap")]
+use masking::{ExposeInterface, Secret};
use crate::{
- consts::{JWT_TOKEN_COOKIE_NAME, JWT_TOKEN_TIME_IN_SECS},
+ consts::JWT_TOKEN_COOKIE_NAME,
+ core::errors::{ApiErrorResponse, RouterResult},
+};
+#[cfg(feature = "olap")]
+use crate::{
+ consts::JWT_TOKEN_TIME_IN_SECS,
core::errors::{UserErrors, UserResponse},
services::ApplicationResponse,
};
+#[cfg(feature = "olap")]
pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> {
let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS
.try_into()
@@ -19,16 +31,17 @@ pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserRespons
let header_value = create_cookie(token, expiry, max_age)
.to_string()
.into_masked();
- let header_key = get_cookie_header();
+ let header_key = get_set_cookie_header();
let header = vec![(header_key, header_value)];
Ok(ApplicationResponse::JsonWithHeaders((response, header)))
}
+#[cfg(feature = "olap")]
pub fn remove_cookie_response() -> UserResponse<()> {
let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0);
- let header_key = get_cookie_header();
+ let header_key = get_set_cookie_header();
let header_value = create_cookie("".to_string().into(), expiry, max_age)
.to_string()
.into_masked();
@@ -36,6 +49,19 @@ pub fn remove_cookie_response() -> UserResponse<()> {
Ok(ApplicationResponse::JsonWithHeaders(((), header)))
}
+pub fn parse_cookie(cookies: &str) -> RouterResult<String> {
+ Cookie::split_parse(cookies)
+ .find_map(|cookie| {
+ cookie
+ .ok()
+ .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME)
+ .map(|parsed_cookie| parsed_cookie.value().to_owned())
+ })
+ .ok_or(report!(ApiErrorResponse::InvalidCookie))
+ .attach_printable("Cookie Parsing Failed")
+}
+
+#[cfg(feature = "olap")]
fn create_cookie<'c>(
token: Secret<String>,
expires: OffsetDateTime,
@@ -51,12 +77,18 @@ fn create_cookie<'c>(
.build()
}
+#[cfg(feature = "olap")]
fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) {
let max_age = Duration::seconds(seconds);
let expiry = OffsetDateTime::now_utc().saturating_add(max_age);
(expiry, max_age)
}
-fn get_cookie_header() -> String {
+#[cfg(feature = "olap")]
+fn get_set_cookie_header() -> String {
actix_http::header::SET_COOKIE.to_string()
}
+
+pub fn get_cookie_header() -> String {
+ actix_http::header::COOKIE.to_string()
+}
|
2024-04-04T10:50:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This is the second PR for cookie implementation.
In this PR, cookie header is parsed to retrieve JWT that was set during dashboard entry.
This PR does not remove old auth flow where `Authorization` header was used to retrieve JWT from request. Instead, it compares the JWT retrieved from `Authorization` header and `Cookie` header and logs the result.
<!-- 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
Storing JWT in cookies instead of local storage.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
No testing required, feature is not complete and hence is not enabled.
<!--
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
|
63d2b6855acee1adeae2efff10f424e056af0bcb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4295
|
Bug: [Refactor] Log the appropriate error message
### Feature Description
Log the appropriate error message when there's an error while saving the card In the locker
### Possible Implementation
Log the appropriate error message when there's an error while saving the card In the locker
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index a5132e4a346..f891f44f099 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -140,7 +140,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
resp.payment_method_id = payment_method_id.clone();
resp.payment_method_status = payment_method_status;
}
- Err(_) => logger::error!("Save pm to locker failed"),
+ Err(err) => logger::error!("Save pm to locker failed : {err:?}"),
}
Ok(resp)
|
2024-04-04T09:11:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
log the appropriate error message if the card fails to get saved in locker
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
Cannot be tested , just a log addition
## Checklist
<!-- Put 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
|
21e2d78117a9e25708b8c6a2280f6a836ee86072
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4288
|
Bug: refactor: fix typos in stripe transformers
Fix typos caught from the new version of typos-cli
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index ef613ed7cfe..76733a19ca3 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2427,12 +2427,12 @@ impl<F, T>
services::RedirectForm::from((redirection_url, services::Method::Get))
});
- let mandate_reference = item.response.payment_method.map(|paymet_method_id| {
+ let mandate_reference = item.response.payment_method.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
- // For backward compataibility payment_method_id & connector_mandate_id is being populated with the same value
- let connector_mandate_id = Some(paymet_method_id.clone().expose());
- let payment_method_id = Some(paymet_method_id.expose());
+ // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
+ let connector_mandate_id = Some(payment_method_id.clone().expose());
+ let payment_method_id = Some(payment_method_id.expose());
types::MandateReference {
connector_mandate_id,
payment_method_id,
@@ -2559,11 +2559,11 @@ impl<F, T>
.response
.payment_method
.clone()
- .map(|paymet_method_id| {
+ .map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
- // For backward compataibility payment_method_id & connector_mandate_id is being populated with the same value
- let connector_mandate_id = Some(paymet_method_id.clone().expose());
+ // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
+ let connector_mandate_id = Some(payment_method_id.clone().expose());
let payment_method_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge)) => {
match charge.payment_method_details {
@@ -2571,16 +2571,16 @@ impl<F, T>
bancontact
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
- .unwrap_or(paymet_method_id.expose())
+ .unwrap_or(payment_method_id.expose())
}
Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
- .unwrap_or(paymet_method_id.expose()),
+ .unwrap_or(payment_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
- .unwrap_or(paymet_method_id.expose()),
+ .unwrap_or(payment_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Blik)
| Some(StripePaymentMethodDetailsResponse::Eps)
| Some(StripePaymentMethodDetailsResponse::Fpx)
@@ -2598,10 +2598,10 @@ impl<F, T>
| Some(StripePaymentMethodDetailsResponse::Wechatpay)
| Some(StripePaymentMethodDetailsResponse::Alipay)
| Some(StripePaymentMethodDetailsResponse::CustomerBalance)
- | None => paymet_method_id.expose(),
+ | None => payment_method_id.expose(),
}
}
- Some(StripeChargeEnum::ChargeId(_)) | None => paymet_method_id.expose(),
+ Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id.expose(),
};
types::MandateReference {
connector_mandate_id,
@@ -2663,12 +2663,12 @@ impl<F, T>
services::RedirectForm::from((redirection_url, services::Method::Get))
});
- let mandate_reference = item.response.payment_method.map(|paymet_method_id| {
+ let mandate_reference = item.response.payment_method.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
- // For backward compataibility payment_method_id & connector_mandate_id is being populated with the same value
- let connector_mandate_id = Some(paymet_method_id.clone());
- let payment_method_id = Some(paymet_method_id);
+ // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
+ let connector_mandate_id = Some(payment_method_id.clone());
+ let payment_method_id = Some(payment_method_id);
types::MandateReference {
connector_mandate_id,
payment_method_id,
|
2024-04-03T11:18:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR fixes typos caught from the new version of typos-cli
### 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)?
-->
Local sanity testing
## Checklist
<!-- Put an `x` in 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
|
4051cbb4e7f708267b26439061e001bb00342cad
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4283
|
Bug: [REFACTOR]: add `updated` field to payments response
Add a field called `updated` to the payments response. This field will have the ISO timestamp at which the payment was updated.
This field should have the value from `modified_at` column from the `payment_intent` table.
The struct that is being used for the response is
https://github.com/juspay/hyperswitch/blob/97fbc899c12a0c66ac89a7feaa6d45d39239a746/crates/api_models/src/payments.rs#L2910
In order to populate the field, use the builder method `.set_updated` when the response is generated
https://github.com/juspay/hyperswitch/blob/97fbc899c12a0c66ac89a7feaa6d45d39239a746/crates/router/src/core/payments/transformers.rs#L792
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index de8142ddde2..99ae68c2e7d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3196,6 +3196,11 @@ pub struct PaymentsResponse {
/// Payment Method Status
#[schema(value_type = Option<PaymentMethodStatus>)]
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
+
+ /// Date time at which payment was updated
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub updated: Option<PrimitiveDateTime>,
}
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)]
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 595ca3f94a9..7b1a8ffd0ff 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -773,6 +773,7 @@ where
.set_payment_method_status(payment_data.payment_method_info.map(|info| info.status))
.set_customer(customer_details_response.clone())
.set_browser_info(payment_attempt.browser_info)
+ .set_updated(Some(payment_intent.modified_at))
.to_owned(),
headers,
))
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index aacc1386411..d2610a0d94c 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -14832,6 +14832,13 @@
}
],
"nullable": true
+ },
+ "updated": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Date time at which payment was updated",
+ "example": "2022-09-10T10:11:12Z",
+ "nullable": true
}
}
},
|
2024-04-03T19:55:15Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [X] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- -->
This change adds the `updated` field to the PaymentResponse.
It takes the value from the `payment_intent.modified_at` field.
### 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.
-->
https://github.com/juspay/hyperswitch/blob/97fbc899c12a0c66ac89a7feaa6d45d39239a746/crates/router/src/core/payments/transformers.rs#L792
https://github.com/juspay/hyperswitch/blob/97fbc899c12a0c66ac89a7feaa6d45d39239a746/crates/api_models/src/payments.rs#L3195
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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 https://github.com/juspay/hyperswitch/issues/4283
## How did you test 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 the below curl
```bash
curl --location 'https://integ-api.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'api-key: <api_key>' \
--data '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "Narayan Bhat",
"card_cvc": "123"
}
}
}'
```
Check for the `updated` field in response.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [X] I reviewed the submitted code
|
7b4c4fea332d56f81a73b496fa0fefdbb64b3648
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4290
|
Bug: [Patch]: make locker call sync to pupulate pm_id
Sample curl:
### `Payment Create` with confirm as true:
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_vEXG9ROzIB0Mg0v43nHhIp7yA3zGl6XkiEKd5RekoXbUUiB9OIF4VRlBWYjdzToU' \
--data-raw '{
"amount": 150,
"currency": "USD",
"confirm": true,
"profile_id": "pro_QCRgQVCzV1nySudvYgIe",
"capture_method": "automatic",
"customer_id": "cus_1RzIEX1NgYo6fLeGjgtv",
"amount_to_capture": 150,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5555 5555 5555 4444",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"phone_country_code": "+65",
"authentication_type": "three_ds",
"description": "Its my first payment request",
"return_url": "https://google.com",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"metadata": {
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
}
'
```
Response should include pm_id
```
{
"payment_id": "pay_yL8fXbw3pbRlJSRX4e7a",
"merchant_id": "merchant_1711530541",
"status": "requires_customer_action",
"amount": 150,
"net_amount": 150,
"amount_capturable": 150,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_yL8fXbw3pbRlJSRX4e7a_secret_vwCOaRzAJMljn8SBDSm5",
"created": "2024-04-03T12:33:58.442Z",
"currency": "USD",
"customer_id": "cus_1RzIEX1NgYo6fLeGjgtv",
"customer": {
"id": "cus_1RzIEX1NgYo6fLeGjgtv",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4444",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "555555",
"card_extended_bin": "55555555",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_yL8fXbw3pbRlJSRX4e7a/merchant_1711530541/pay_yL8fXbw3pbRlJSRX4e7a_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cus_1RzIEX1NgYo6fLeGjgtv",
"created_at": 1712147638,
"expires": 1712151238,
"secret": "epk_e4aed6ba27104cae922e7eca3abac9a1"
},
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3P1T0sCuXDMKrYZe0aiQy6I9",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1T0sCuXDMKrYZe0aiQy6I9",
"payment_link": null,
"profile_id": "pro_QCRgQVCzV1nySudvYgIe",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_fIdf9xGkZ1oFaetaZ3Gu",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-03T12:48:58.442Z",
"fingerprint": null,
"browser_info": null,
**"payment_method_id": "pm_SCw1B5EgzNSOBf89mDd7",**
"payment_method_status": null
}
```
|
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 8984c1caeeb..6c236729de4 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -347,7 +347,7 @@ pub enum PaymentAttemptUpdate {
connector: Option<String>,
connector_transaction_id: Option<String>,
authentication_type: Option<storage_enums::AuthenticationType>,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
mandate_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
payment_token: Option<String>,
@@ -367,7 +367,7 @@ pub enum PaymentAttemptUpdate {
status: storage_enums::AttemptStatus,
connector: Option<String>,
connector_transaction_id: Option<String>,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
@@ -403,7 +403,7 @@ pub enum PaymentAttemptUpdate {
},
PreprocessingUpdate {
status: storage_enums::AttemptStatus,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
preprocessing_step_id: Option<String>,
connector_transaction_id: Option<String>,
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 77fd21165d7..6ad21eab12b 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -254,7 +254,7 @@ pub enum PaymentAttemptUpdate {
connector: Option<String>,
connector_transaction_id: Option<String>,
authentication_type: Option<storage_enums::AuthenticationType>,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
mandate_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
payment_token: Option<String>,
@@ -274,7 +274,7 @@ pub enum PaymentAttemptUpdate {
status: storage_enums::AttemptStatus,
connector: Option<String>,
connector_transaction_id: Option<String>,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
@@ -310,7 +310,7 @@ pub enum PaymentAttemptUpdate {
},
PreprocessingUpdate {
status: storage_enums::AttemptStatus,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
preprocessing_step_id: Option<String>,
connector_transaction_id: Option<String>,
@@ -350,7 +350,7 @@ pub struct PaymentAttemptUpdateInternal {
authentication_type: Option<storage_enums::AuthenticationType>,
payment_method: Option<storage_enums::PaymentMethod>,
error_message: Option<Option<String>>,
- payment_method_id: Option<Option<String>>,
+ payment_method_id: Option<String>,
cancellation_reason: Option<String>,
modified_at: Option<PrimitiveDateTime>,
mandate_id: Option<String>,
@@ -459,7 +459,7 @@ impl PaymentAttemptUpdate {
authentication_type: authentication_type.or(source.authentication_type),
payment_method: payment_method.or(source.payment_method),
error_message: error_message.unwrap_or(source.error_message),
- payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
+ payment_method_id: payment_method_id.or(source.payment_method_id),
cancellation_reason: cancellation_reason.or(source.cancellation_reason),
modified_at: common_utils::date_time::now(),
mandate_id: mandate_id.or(source.mandate_id),
@@ -605,7 +605,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
authentication_id,
payment_method_billing_address_id,
fingerprint_id,
- payment_method_id: payment_method_id.map(Some),
+ payment_method_id,
..Default::default()
},
PaymentAttemptUpdate::VoidUpdate {
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 87c93af6635..e7ec99f61b6 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2136,7 +2136,9 @@ where
)
.await?;
payment_data.payment_method_data = payment_method_data;
- payment_data.payment_attempt.payment_method_id = pm_id;
+ if let Some(payment_method_id) = pm_id {
+ payment_data.payment_attempt.payment_method_id = Some(payment_method_id);
+ }
payment_data
} else {
payment_data
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index bc43839fdcb..a5132e4a346 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -1,7 +1,7 @@
use async_trait::async_trait;
use error_stack;
-use router_env::tracing::Instrument;
+// use router_env::tracing::Instrument;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
@@ -118,43 +118,65 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
)
.await?)
} else {
- let connector = connector.clone();
let response = resp.clone();
- let maybe_customer = maybe_customer.clone();
- let merchant_account = merchant_account.clone();
- let key_store = key_store.clone();
- let state = state.clone();
logger::info!("Call to save_payment_method in locker");
- let _task_handle = tokio::spawn(
- async move {
- logger::info!("Starting async call to save_payment_method in locker");
-
- let result = Box::pin(tokenization::save_payment_method(
- &state,
- &connector,
- response,
- &maybe_customer,
- &merchant_account,
- self.request.payment_method_type,
- &key_store,
- Some(resp.request.amount),
- Some(resp.request.currency),
- ))
- .await;
-
- if let Err(err) = result {
- logger::error!(
- "Asynchronously saving card in locker failed : {:?}",
- err
- );
- }
+
+ let pm = Box::pin(tokenization::save_payment_method(
+ state,
+ connector,
+ response,
+ maybe_customer,
+ merchant_account,
+ self.request.payment_method_type,
+ key_store,
+ Some(resp.request.amount),
+ Some(resp.request.currency),
+ ))
+ .await;
+
+ match pm {
+ Ok((payment_method_id, payment_method_status)) => {
+ resp.payment_method_id = payment_method_id.clone();
+ resp.payment_method_status = payment_method_status;
}
- .in_current_span(),
- );
+ Err(_) => logger::error!("Save pm to locker failed"),
+ }
Ok(resp)
}
+
+ // Async locker code (Commenting out the code for near future refactors)
+ // logger::info!("Call to save_payment_method in locker");
+ // let _task_handle = tokio::spawn(
+ // async move {
+ // logger::info!("Starting async call to save_payment_method in locker");
+ //
+ // let result = Box::pin(tokenization::save_payment_method(
+ // &state,
+ // &connector,
+ // response,
+ // &maybe_customer,
+ // &merchant_account,
+ // self.request.payment_method_type,
+ // &key_store,
+ // Some(resp.request.amount),
+ // Some(resp.request.currency),
+ // ))
+ // .await;
+ //
+ // if let Err(err) = result {
+ // logger::error!(
+ // "Asynchronously saving card in locker failed : {:?}",
+ // err
+ // );
+ // }
+ // }
+ // .in_current_span(),
+ // );
+ //
+ // Ok(resp)
+ // }
} else {
Ok(self.clone())
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6cb19a29a1d..66f35e63b2c 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -587,7 +587,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
let payment_attempt_update =
storage::PaymentAttemptUpdate::PreprocessingUpdate {
status: updated_attempt_status,
- payment_method_id: Some(router_data.payment_method_id),
+ payment_method_id: router_data.payment_method_id,
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
@@ -676,7 +676,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
amount_capturable: router_data
.request
.get_amount_capturable(&payment_data, updated_attempt_status),
- payment_method_id: Some(payment_method_id),
+ payment_method_id,
mandate_id: payment_data
.mandate_id
.clone()
@@ -715,7 +715,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
status: updated_attempt_status,
connector: None,
connector_transaction_id,
- payment_method_id: Some(router_data.payment_method_id),
+ payment_method_id: router_data.payment_method_id,
error_code: Some(reason.clone().map(|cd| cd.code)),
error_message: Some(reason.clone().map(|cd| cd.message)),
error_reason: Some(reason.map(|cd| cd.message)),
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 09400bb750b..3eeecdba3a8 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -376,7 +376,7 @@ where
.connector_response_reference_id
.clone(),
authentication_type: None,
- payment_method_id: Some(router_data.payment_method_id),
+ payment_method_id: router_data.payment_method_id,
mandate_id: payment_data
.mandate_id
.clone()
|
2024-04-03T12:38:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Making the locker call synchronous in order to update pm_id in payment response.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Sample curl:
### `Payment Create` with confirm as true:
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_vEXG9ROzIB0Mg0v43nHhIp7yA3zGl6XkiEKd5RekoXbUUiB9OIF4VRlBWYjdzToU' \
--data-raw '{
"amount": 150,
"currency": "USD",
"confirm": true,
"profile_id": "pro_QCRgQVCzV1nySudvYgIe",
"capture_method": "automatic",
"customer_id": "cus_1RzIEX1NgYo6fLeGjgtv",
"amount_to_capture": 150,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5555 5555 5555 4444",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"phone_country_code": "+65",
"authentication_type": "three_ds",
"description": "Its my first payment request",
"return_url": "https://google.com",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"metadata": {
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
}
'
```
Response should include pm_id
```
{
"payment_id": "pay_yL8fXbw3pbRlJSRX4e7a",
"merchant_id": "merchant_1711530541",
"status": "requires_customer_action",
"amount": 150,
"net_amount": 150,
"amount_capturable": 150,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_yL8fXbw3pbRlJSRX4e7a_secret_vwCOaRzAJMljn8SBDSm5",
"created": "2024-04-03T12:33:58.442Z",
"currency": "USD",
"customer_id": "cus_1RzIEX1NgYo6fLeGjgtv",
"customer": {
"id": "cus_1RzIEX1NgYo6fLeGjgtv",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4444",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "555555",
"card_extended_bin": "55555555",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_yL8fXbw3pbRlJSRX4e7a/merchant_1711530541/pay_yL8fXbw3pbRlJSRX4e7a_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cus_1RzIEX1NgYo6fLeGjgtv",
"created_at": 1712147638,
"expires": 1712151238,
"secret": "epk_e4aed6ba27104cae922e7eca3abac9a1"
},
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3P1T0sCuXDMKrYZe0aiQy6I9",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1T0sCuXDMKrYZe0aiQy6I9",
"payment_link": null,
"profile_id": "pro_QCRgQVCzV1nySudvYgIe",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_fIdf9xGkZ1oFaetaZ3Gu",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-03T12:48:58.442Z",
"fingerprint": null,
"browser_info": null,
**"payment_method_id": "pm_SCw1B5EgzNSOBf89mDd7",**
"payment_method_status": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
8efd468ac150ff8d28f5b44b25701ba1837f243d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4282
|
Bug: [REFACTOR] : [Stripe] fix Mandate flow
### Feature Description
Earlier the connector_mandate_id was not being populated as expected, instead it was being populated in a separate field as payment_method_id in mandate_reference data. In this PR the flow has been refactored and fixed to send the Response from connector such that it is mapped to the connector_mandate_id in the core.
### Have you spent some time to check if this feature request has been raised before?
- [X] I checked and didn't find similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
yes
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 4673cce4d81..18776bcba43 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -124,7 +124,6 @@ pub struct PaymentIntentRequest {
pub meta_data: HashMap<String, String>,
pub return_url: String,
pub confirm: bool,
- pub mandate: Option<Secret<String>>,
pub payment_method: Option<String>,
pub customer: Option<Secret<String>>,
#[serde(flatten)]
@@ -1800,7 +1799,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
};
let mut payment_method_options = None;
- let (mut payment_data, payment_method, mandate, billing_address, payment_method_types) = {
+ let (mut payment_data, payment_method, billing_address, payment_method_types) = {
match item
.request
.mandate_id
@@ -1811,7 +1810,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
connector_mandate_ids,
)) => (
None,
- connector_mandate_ids.payment_method_id,
connector_mandate_ids.connector_mandate_id,
StripeBillingAddress::default(),
get_payment_method_type_for_saved_payment_method_payment(item)?,
@@ -1826,7 +1824,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
network_transaction_id: Secret::new(network_transaction_id),
}),
});
- (None, None, None, StripeBillingAddress::default(), None)
+ (None, None, StripeBillingAddress::default(), None)
}
_ => {
let (payment_method_data, payment_method_type, billing_address) =
@@ -1848,7 +1846,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
(
Some(payment_method_data),
None,
- None,
billing_address,
payment_method_type,
)
@@ -1965,7 +1962,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
billing: billing_address,
capture_method: StripeCaptureMethod::from(item.request.capture_method),
payment_data,
- mandate: mandate.map(Secret::new),
payment_method_options,
payment_method,
customer: item.connector_customer.to_owned().map(Secret::new),
@@ -2416,40 +2412,6 @@ fn extract_payment_method_connector_response_from_latest_attempt(
.map(types::ConnectorResponseData::with_additional_payment_method_data)
}
-impl ForeignFrom<(Option<StripePaymentMethodOptions>, String)> for types::MandateReference {
- fn foreign_from(
- (payment_method_options, payment_method_id): (Option<StripePaymentMethodOptions>, String),
- ) -> Self {
- Self {
- connector_mandate_id: payment_method_options.and_then(|options| match options {
- StripePaymentMethodOptions::Card {
- mandate_options, ..
- } => mandate_options.map(|mandate_options| mandate_options.reference.expose()),
- StripePaymentMethodOptions::Klarna {}
- | StripePaymentMethodOptions::Affirm {}
- | StripePaymentMethodOptions::AfterpayClearpay {}
- | StripePaymentMethodOptions::Eps {}
- | StripePaymentMethodOptions::Giropay {}
- | StripePaymentMethodOptions::Ideal {}
- | StripePaymentMethodOptions::Sofort {}
- | StripePaymentMethodOptions::Ach {}
- | StripePaymentMethodOptions::Bacs {}
- | StripePaymentMethodOptions::Becs {}
- | StripePaymentMethodOptions::WechatPay {}
- | StripePaymentMethodOptions::Alipay {}
- | StripePaymentMethodOptions::Sepa {}
- | StripePaymentMethodOptions::Bancontact {}
- | StripePaymentMethodOptions::Przelewy24 {}
- | StripePaymentMethodOptions::CustomerBalance {}
- | StripePaymentMethodOptions::Blik {}
- | StripePaymentMethodOptions::Multibanco {}
- | StripePaymentMethodOptions::Cashapp {} => None,
- }),
- payment_method_id: Some(payment_method_id),
- }
- }
-}
-
impl<F, T>
TryFrom<types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>>
for types::RouterData<F, T, types::PaymentsResponseData>
@@ -2465,11 +2427,16 @@ impl<F, T>
services::RedirectForm::from((redirection_url, services::Method::Get))
});
- let mandate_reference = item.response.payment_method.map(|pm| {
- types::MandateReference::foreign_from((
- item.response.payment_method_options,
- pm.expose(),
- ))
+ let mandate_reference = item.response.payment_method.map(|paymet_method_id| {
+ // Implemented Save and re-use payment information for recurring charges
+ // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
+ // For backward compataibility payment_method_id & connector_mandate_id is being populated with the same value
+ let connector_mandate_id = Some(paymet_method_id.clone().expose());
+ let payment_method_id = Some(paymet_method_id.expose());
+ types::MandateReference {
+ connector_mandate_id,
+ payment_method_id,
+ }
});
//Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse
@@ -2588,26 +2555,32 @@ impl<F, T>
services::RedirectForm::from((redirection_url, services::Method::Get))
});
- let mandate_reference = item.response.payment_method.clone().map(|pm| {
- types::MandateReference::foreign_from((
- item.response.payment_method_options.clone(),
- match item.response.latest_charge.clone() {
+ let mandate_reference = item
+ .response
+ .payment_method
+ .clone()
+ .map(|paymet_method_id| {
+ // Implemented Save and re-use payment information for recurring charges
+ // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
+ // For backward compataibility payment_method_id & connector_mandate_id is being populated with the same value
+ let connector_mandate_id = Some(paymet_method_id.clone().expose());
+ let payment_method_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge)) => {
match charge.payment_method_details {
Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => {
bancontact
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
- .unwrap_or(pm.expose())
+ .unwrap_or(paymet_method_id.expose())
}
Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
- .unwrap_or(pm.expose()),
+ .unwrap_or(paymet_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
- .unwrap_or(pm.expose()),
+ .unwrap_or(paymet_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Blik)
| Some(StripePaymentMethodDetailsResponse::Eps)
| Some(StripePaymentMethodDetailsResponse::Fpx)
@@ -2625,13 +2598,16 @@ impl<F, T>
| Some(StripePaymentMethodDetailsResponse::Wechatpay)
| Some(StripePaymentMethodDetailsResponse::Alipay)
| Some(StripePaymentMethodDetailsResponse::CustomerBalance)
- | None => pm.expose(),
+ | None => paymet_method_id.expose(),
}
}
- Some(StripeChargeEnum::ChargeId(_)) | None => pm.expose(),
- },
- ))
- });
+ Some(StripeChargeEnum::ChargeId(_)) | None => paymet_method_id.expose(),
+ };
+ types::MandateReference {
+ connector_mandate_id,
+ payment_method_id: Some(payment_method_id),
+ }
+ });
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
@@ -2687,8 +2663,16 @@ impl<F, T>
services::RedirectForm::from((redirection_url, services::Method::Get))
});
- let mandate_reference = item.response.payment_method.map(|pm| {
- types::MandateReference::foreign_from((item.response.payment_method_options, pm))
+ let mandate_reference = item.response.payment_method.map(|paymet_method_id| {
+ // Implemented Save and re-use payment information for recurring charges
+ // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
+ // For backward compataibility payment_method_id & connector_mandate_id is being populated with the same value
+ let connector_mandate_id = Some(paymet_method_id.clone());
+ let payment_method_id = Some(paymet_method_id);
+ types::MandateReference {
+ connector_mandate_id,
+ payment_method_id,
+ }
});
let status = enums::AttemptStatus::from(item.response.status);
let connector_response_data = item
|
2024-04-03T06:45:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Earlier the connector_mandate_id was not being populated as expected, instead it was being populated in a separate field as `payment_method_id` in mandate_reference data. And earlier if we try to do MIT payment using `payment_method_id` it was not working. In this PR the flow has been refactored and fixed to send the Response from connector such that it is mapped to the `connector_mandate_id` in the core.
### 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?
1. Create a CIT Card payment via Stripe Connector.
```{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "SWANGI123",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"setup_future_usage" : "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}
```
Response
```
{
"payment_id": "pay_W8etDYfDKWRbDIn09D4U",
"merchant_id": "postman_merchant_GHAction_d77decd1-f90c-4746-acbf-ab8dd9d535a7",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_W8etDYfDKWRbDIn09D4U_secret_lGSLQbpiCobpLFr17nCb",
"created": "2024-04-03T05:50:06.402Z",
"currency": "USD",
"customer_id": "SWANGI123",
"customer": {
"id": "SWANGI123",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"address_line1_check": null,
"address_postal_code_check": null,
"cvc_check": "pass"
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "SWANGI123",
"created_at": 1712123406,
"expires": 1712127006,
"secret": "epk_c17fa3fa8a6046349669f9ad4a6c0ac8"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3P1Mi3D5R7gDAGff1hkHBS5N",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P1Mi3D5R7gDAGff1hkHBS5N",
"payment_link": null,
"profile_id": "pro_7kS7x2eFLd119TxUPlRq",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_dWmQ6lhUUo9rUXfB5vbF",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-03T06:05:06.402Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
hit List Payment methods for a Customer
Response:
```
{
"customer_payment_methods": [
{
"payment_token": "token_FwaoCK5rxMkaapn3GQuu",
"payment_method_id": "pm_aV6lBMNaXPHFCzujobVL",
"customer_id": "SWANGI123",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "25",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-04-03T05:50:08.940Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-04-03T05:50:08.940Z",
"default_payment_method_set": false
},
{
"payment_token": "token_ZH3KUgh1tBQMm3yj2FaI",
"payment_method_id": "pm_QfcwtyKLOS7ROJKB3mhV",
"customer_id": "SWANGI123",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "25",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-04-02T13:50:05.528Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-04-02T13:50:05.528Z",
"default_payment_method_set": true
}
],
"is_guest_customer": null
}
```
In Response we will get `payment_method_id` .
Using this payment_method_id we will create MIT
```
{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "SWANGI123",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"off_session": true,
"recurring_details":{
"type":"payment_method_id",
"data":"{{payment_method_id}}"
}
}
```
## Checklist
<!-- Put an `x` in 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
|
1c63c5268be87124b75cdc2d901a80123996a0a7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4262
|
Bug: refactor(mandates): add validations for recurring mandates using payment_method_id
When a setup mandate is done with customer, when doing recurring payment using `payment_method_id`, add validation to match on customer_id such that they match on setup mandate as well as recurring.
Also add validation not to pass both `mandate_id` and `recurring_details`
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index f08a793ebf5..78140ea2932 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -282,6 +282,28 @@ fn saved_in_locker_default() -> bool {
true
}
+impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {
+ fn from(item: CardDetailFromLocker) -> Self {
+ Self {
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type,
+ card_issuing_country: item.issuer_country,
+ bank_code: None,
+ last4: item.last4_digits,
+ card_isin: item.card_isin,
+ card_extended_bin: item
+ .card_number
+ .map(|card_number| card_number.get_card_extended_bin()),
+ card_exp_month: item.expiry_month,
+ card_exp_year: item.expiry_year,
+ card_holder_name: item.card_holder_name,
+ payment_checks: None,
+ authentication_data: None,
+ }
+ }
+}
+
impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
fn from(item: CardDetailsPaymentMethod) -> Self {
Self {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 0f80b6a52ea..1116e49a4e5 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -469,6 +469,18 @@ pub async fn get_token_pm_type_mandate_details(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
+ let customer_id = request
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
+
+ verify_mandate_details_for_recurring_payments(
+ &payment_method_info.merchant_id,
+ &merchant_account.merchant_id,
+ &payment_method_info.customer_id,
+ &customer_id,
+ )?;
+
(
None,
Some(payment_method_info.payment_method),
@@ -869,6 +881,7 @@ pub fn validate_mandate(
pub fn validate_recurring_details_and_token(
recurring_details: &Option<RecurringDetails>,
payment_token: &Option<String>,
+ mandate_id: &Option<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
utils::when(
recurring_details.is_some() && payment_token.is_some(),
@@ -880,6 +893,12 @@ pub fn validate_recurring_details_and_token(
},
)?;
+ utils::when(recurring_details.is_some() && mandate_id.is_some(), || {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Expected one out of recurring_details and mandate_id but got both".into()
+ }))
+ })?;
+
Ok(())
}
@@ -1080,6 +1099,24 @@ pub fn verify_mandate_details(
)
}
+pub fn verify_mandate_details_for_recurring_payments(
+ mandate_merchant_id: &str,
+ merchant_id: &str,
+ mandate_customer_id: &str,
+ customer_id: &str,
+) -> RouterResult<()> {
+ if mandate_merchant_id != merchant_id {
+ Err(report!(errors::ApiErrorResponse::MandateNotFound))?
+ }
+ if mandate_customer_id != customer_id {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "customer_id must match mandate customer_id".into()
+ }))?
+ }
+
+ Ok(())
+}
+
#[instrument(skip_all)]
pub fn payment_attempt_status_fsm(
payment_method_data: &Option<api::payments::PaymentMethodDataRequest>,
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 9d0971982a6..ccefb3b2b53 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -461,6 +461,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
+ &request.mandate_id,
)?;
Ok((
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index eca8d2d90f6..4eac9c1f4de 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1205,6 +1205,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
+ &request.mandate_id,
)?;
let payment_id = request
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 6dce6db9d9b..80b7d52d31e 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1,15 +1,17 @@
use std::marker::PhantomData;
-use api_models::{enums::FrmSuggestion, mandates::RecurringDetails};
+use api_models::{
+ enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,
+};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use data_models::{
mandates::{MandateData, MandateDetails},
payments::payment_attempt::PaymentAttempt,
};
-use diesel_models::ephemeral_key;
+use diesel_models::{ephemeral_key, PaymentMethod};
use error_stack::{self, ResultExt};
-use masking::PeekInterface;
+use masking::{ExposeInterface, PeekInterface};
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use time::PrimitiveDateTime;
@@ -259,6 +261,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_method_billing_address
.as_ref()
.map(|address| address.address_id.clone()),
+ &payment_method_info,
+ merchant_key_store,
)
.await?;
@@ -690,6 +694,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
+ &request.mandate_id,
)?;
if request.confirm.unwrap_or(false) {
@@ -743,6 +748,8 @@ impl PaymentCreate {
browser_info: Option<serde_json::Value>,
state: &AppState,
payment_method_billing_address_id: Option<String>,
+ payment_method_info: &Option<PaymentMethod>,
+ key_store: &domain::MerchantKeyStore,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
@@ -752,7 +759,7 @@ impl PaymentCreate {
helpers::payment_attempt_status_fsm(&request.payment_method_data, request.confirm);
let (amount, currency) = (money.0, Some(money.1));
- let additional_pm_data = request
+ let mut additional_pm_data = request
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
@@ -763,6 +770,35 @@ impl PaymentCreate {
.await
})
.await;
+
+ if additional_pm_data.is_none() {
+ // If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object
+ additional_pm_data = payment_method_info
+ .as_ref()
+ .async_map(|pm_info| async {
+ domain::types::decrypt::<serde_json::Value, masking::WithType>(
+ pm_info.payment_method_data.clone(),
+ key_store.key.get_inner().peek(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ .attach_printable("unable to decrypt card details")
+ .ok()
+ .flatten()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ })
+ })
+ .await
+ .flatten()
+ .map(|card| {
+ api_models::payments::AdditionalPaymentData::Card(Box::new(card.into()))
+ })
+ };
+
let additional_pm_data_value = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
@@ -841,7 +877,9 @@ impl PaymentCreate {
connector: None,
error_message: None,
offer_amount: None,
- payment_method_id: None,
+ payment_method_id: payment_method_info
+ .as_ref()
+ .map(|pm_info| pm_info.payment_method_id.clone()),
cancellation_reason: None,
error_code: None,
connector_metadata: None,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index a6a41732f1b..76c28307dba 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -754,6 +754,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
+ &request.mandate_id,
)?;
Ok((
|
2024-04-01T11:06:37Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
When a setup mandate is done with customer, when doing recurring payment using `payment_method_id`, this PR adds following validation
- to match on customer_id such that they match on setup mandate as well as recurring.
- to match on merchant_id such that they match on setup mandate as well as recurring.
- not to pass both `mandate_id` and `recurring_details`
This PR also stores `payment_method_id` and `payment_method_data` in payment_attempt table when doing recurring payment with `payment_method_id`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Setup mandate with a customer
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "test_cus4",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "online"
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"card_cvc": "737"
}
},
"payment_type": "setup_mandate",
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "153.54.53.134",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": null
}
}
}'
```
2. Now try to do recurring payment using`payment_method_id` by passing different customer_id
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "test_cus5",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "xyz"
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds"
}'
```

3. Now try to pass both `mandate_id` and `recurring_details`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "test_cus4",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_7zf8MTSyG3h6grOBwPPc"
},
"mandate_id": "abc",
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds"
}'
```

4. When recurring payment is done using `payment_method_id`, both `payment_method_id` and `payment_method_data` is getting stored in attempt table

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
97fbc899c12a0c66ac89a7feaa6d45d39239a746
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4284
|
Bug: [GLOBALSEARCH] - modular code refactoring with health check
- code refactoring for opensearch module
- deep health check addition
|
diff --git a/Cargo.lock b/Cargo.lock
index b4819f9f379..635edcc995e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -337,6 +337,7 @@ dependencies = [
"aws-smithy-types 1.1.8",
"bigdecimal",
"common_utils",
+ "data_models",
"diesel_models",
"error-stack",
"external_services",
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index c3e35519dce..b6cd29badee 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -11,14 +11,22 @@ license.workspace = true
[dependencies]
# First party crates
-api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] }
+api_models = { version = "0.1.0", path = "../api_models", features = [
+ "errors",
+] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
common_utils = { version = "0.1.0", path = "../common_utils" }
external_services = { version = "0.1.0", path = "../external_services", default-features = false }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }
masking = { version = "0.1.0", path = "../masking" }
-router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
-diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
+router_env = { version = "0.1.0", path = "../router_env", features = [
+ "log_extra_implicit_fields",
+ "log_custom_entries_to_extra",
+] }
+diesel_models = { version = "0.1.0", path = "../diesel_models", features = [
+ "kv_store",
+] }
+data_models = { version = "0.1.0", path = "../data_models", default-features = false }
#Third Party dependencies
actix-web = "4.5.1"
@@ -34,7 +42,13 @@ once_cell = "1.19.0"
reqwest = { version = "0.11.27", features = ["serde_json"] }
serde = { version = "1.0.197", features = ["derive", "rc"] }
serde_json = "1.0.115"
-sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] }
+sqlx = { version = "0.7.3", features = [
+ "postgres",
+ "runtime-tokio",
+ "runtime-tokio-native-tls",
+ "time",
+ "bigdecimal",
+] }
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index eb08d8549d1..2a7075a0f29 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -10,6 +10,7 @@ pub mod refunds;
pub mod api_event;
pub mod connector_events;
pub mod health_check;
+pub mod opensearch;
pub mod outgoing_webhook_event;
pub mod sdk_events;
pub mod search;
@@ -668,47 +669,6 @@ pub struct ReportConfig {
pub region: String,
}
-#[derive(Clone, Debug, serde::Deserialize)]
-#[serde(tag = "auth")]
-#[serde(rename_all = "lowercase")]
-pub enum OpensearchAuth {
- Basic { username: String, password: String },
- Aws { region: String },
-}
-
-#[derive(Clone, Debug, serde::Deserialize)]
-pub struct OpensearchIndexes {
- pub payment_attempts: String,
- pub payment_intents: String,
- pub refunds: String,
- pub disputes: String,
-}
-
-#[derive(Clone, Debug, serde::Deserialize)]
-pub struct OpensearchConfig {
- host: String,
- auth: OpensearchAuth,
- indexes: OpensearchIndexes,
-}
-
-impl Default for OpensearchConfig {
- fn default() -> Self {
- Self {
- host: "https://localhost:9200".to_string(),
- auth: OpensearchAuth::Basic {
- username: "admin".to_string(),
- password: "admin".to_string(),
- },
- indexes: OpensearchIndexes {
- payment_attempts: "hyperswitch-payment-attempt-events".to_string(),
- payment_intents: "hyperswitch-payment-intent-events".to_string(),
- refunds: "hyperswitch-refund-events".to_string(),
- disputes: "hyperswitch-dispute-events".to_string(),
- },
- }
- }
-}
-
/// Analytics Flow routes Enums
/// Info - Dimensions and filters available for the domain
/// Filters - Set of values present for the dimension
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
new file mode 100644
index 00000000000..58569338cf6
--- /dev/null
+++ b/crates/analytics/src/opensearch.rs
@@ -0,0 +1,397 @@
+use api_models::{
+ analytics::search::SearchIndex,
+ errors::types::{ApiError, ApiErrorResponse},
+};
+use aws_config::{self, meta::region::RegionProviderChain, Region};
+use common_utils::errors::{CustomResult, ErrorSwitch};
+use data_models::errors::{StorageError, StorageResult};
+use error_stack::ResultExt;
+use opensearch::{
+ auth::Credentials,
+ cert::CertificateValidation,
+ cluster::{Cluster, ClusterHealthParts},
+ http::{
+ request::JsonBody,
+ response::Response,
+ transport::{SingleNodeConnectionPool, Transport, TransportBuilder},
+ Url,
+ },
+ MsearchParts, OpenSearch, SearchParts,
+};
+use serde_json::{json, Value};
+use storage_impl::errors::ApplicationError;
+use strum::IntoEnumIterator;
+
+use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError};
+use crate::query::QueryBuildingError;
+
+#[derive(Clone, Debug, serde::Deserialize)]
+#[serde(tag = "auth")]
+#[serde(rename_all = "lowercase")]
+pub enum OpenSearchAuth {
+ Basic { username: String, password: String },
+ Aws { region: String },
+}
+
+#[derive(Clone, Debug, serde::Deserialize)]
+pub struct OpenSearchIndexes {
+ pub payment_attempts: String,
+ pub payment_intents: String,
+ pub refunds: String,
+ pub disputes: String,
+}
+
+#[derive(Clone, Debug, serde::Deserialize)]
+pub struct OpenSearchConfig {
+ host: String,
+ auth: OpenSearchAuth,
+ indexes: OpenSearchIndexes,
+}
+
+impl Default for OpenSearchConfig {
+ fn default() -> Self {
+ Self {
+ host: "https://localhost:9200".to_string(),
+ auth: OpenSearchAuth::Basic {
+ username: "admin".to_string(),
+ password: "admin".to_string(),
+ },
+ indexes: OpenSearchIndexes {
+ payment_attempts: "hyperswitch-payment-attempt-events".to_string(),
+ payment_intents: "hyperswitch-payment-intent-events".to_string(),
+ refunds: "hyperswitch-refund-events".to_string(),
+ disputes: "hyperswitch-dispute-events".to_string(),
+ },
+ }
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum OpenSearchError {
+ #[error("Opensearch connection error")]
+ ConnectionError,
+ #[error("Opensearch NON-200 response content: '{0}'")]
+ ResponseNotOK(String),
+ #[error("Opensearch response error")]
+ ResponseError,
+ #[error("Opensearch query building error")]
+ QueryBuildingError,
+}
+
+impl ErrorSwitch<OpenSearchError> for QueryBuildingError {
+ fn switch(&self) -> OpenSearchError {
+ OpenSearchError::QueryBuildingError
+ }
+}
+
+impl ErrorSwitch<ApiErrorResponse> for OpenSearchError {
+ fn switch(&self) -> ApiErrorResponse {
+ match self {
+ Self::ConnectionError => ApiErrorResponse::InternalServerError(ApiError::new(
+ "IR",
+ 0,
+ "Connection error",
+ None,
+ )),
+ Self::ResponseNotOK(response) => ApiErrorResponse::InternalServerError(ApiError::new(
+ "IR",
+ 0,
+ format!("Something went wrong {}", response),
+ None,
+ )),
+ Self::ResponseError => ApiErrorResponse::InternalServerError(ApiError::new(
+ "IR",
+ 0,
+ "Something went wrong",
+ None,
+ )),
+ Self::QueryBuildingError => ApiErrorResponse::InternalServerError(ApiError::new(
+ "IR",
+ 0,
+ "Query building error",
+ None,
+ )),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct OpenSearchClient {
+ pub client: OpenSearch,
+ pub transport: Transport,
+ pub indexes: OpenSearchIndexes,
+}
+
+impl OpenSearchClient {
+ pub async fn create(conf: &OpenSearchConfig) -> CustomResult<Self, OpenSearchError> {
+ let url = Url::parse(&conf.host).map_err(|_| OpenSearchError::ConnectionError)?;
+ let transport = match &conf.auth {
+ OpenSearchAuth::Basic { username, password } => {
+ let credentials = Credentials::Basic(username.clone(), password.clone());
+ TransportBuilder::new(SingleNodeConnectionPool::new(url))
+ .cert_validation(CertificateValidation::None)
+ .auth(credentials)
+ .build()
+ .map_err(|_| OpenSearchError::ConnectionError)?
+ }
+ OpenSearchAuth::Aws { region } => {
+ let region_provider = RegionProviderChain::first_try(Region::new(region.clone()));
+ let sdk_config = aws_config::from_env().region(region_provider).load().await;
+ let conn_pool = SingleNodeConnectionPool::new(url);
+ TransportBuilder::new(conn_pool)
+ .auth(
+ sdk_config
+ .clone()
+ .try_into()
+ .map_err(|_| OpenSearchError::ConnectionError)?,
+ )
+ .service_name("es")
+ .build()
+ .map_err(|_| OpenSearchError::ConnectionError)?
+ }
+ };
+ Ok(Self {
+ transport: transport.clone(),
+ client: OpenSearch::new(transport),
+ indexes: conf.indexes.clone(),
+ })
+ }
+
+ pub fn search_index_to_opensearch_index(&self, index: SearchIndex) -> String {
+ match index {
+ SearchIndex::PaymentAttempts => self.indexes.payment_attempts.clone(),
+ SearchIndex::PaymentIntents => self.indexes.payment_intents.clone(),
+ SearchIndex::Refunds => self.indexes.refunds.clone(),
+ SearchIndex::Disputes => self.indexes.disputes.clone(),
+ }
+ }
+
+ pub async fn execute(
+ &self,
+ query_builder: OpenSearchQueryBuilder,
+ ) -> CustomResult<Response, OpenSearchError> {
+ match query_builder.query_type {
+ OpenSearchQuery::Msearch => {
+ let search_indexes = SearchIndex::iter();
+
+ let payload = query_builder
+ .construct_payload(search_indexes.clone().collect())
+ .change_context(OpenSearchError::QueryBuildingError)?;
+
+ let payload_with_indexes = payload.into_iter().zip(search_indexes).fold(
+ Vec::new(),
+ |mut payload_with_indexes, (index_hit, index)| {
+ payload_with_indexes.push(
+ json!({"index": self.search_index_to_opensearch_index(index)}).into(),
+ );
+ payload_with_indexes.push(JsonBody::new(index_hit.clone()));
+ payload_with_indexes
+ },
+ );
+
+ self.client
+ .msearch(MsearchParts::None)
+ .body(payload_with_indexes)
+ .send()
+ .await
+ .change_context(OpenSearchError::ResponseError)
+ }
+ OpenSearchQuery::Search(index) => {
+ let payload = query_builder
+ .clone()
+ .construct_payload(vec![index])
+ .change_context(OpenSearchError::QueryBuildingError)?;
+
+ let final_payload = payload.first().unwrap_or(&Value::Null);
+
+ self.client
+ .search(SearchParts::Index(&[
+ &self.search_index_to_opensearch_index(index)
+ ]))
+ .from(query_builder.offset.unwrap_or(0))
+ .size(query_builder.count.unwrap_or(10))
+ .body(final_payload)
+ .send()
+ .await
+ .change_context(OpenSearchError::ResponseError)
+ }
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl HealthCheck for OpenSearchClient {
+ async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> {
+ let health = Cluster::new(&self.transport)
+ .health(ClusterHealthParts::None)
+ .send()
+ .await
+ .change_context(QueryExecutionError::DatabaseError)?
+ .json::<OpenSearchHealth>()
+ .await
+ .change_context(QueryExecutionError::DatabaseError)?;
+
+ if health.status != OpenSearchHealthStatus::Red {
+ Ok(())
+ } else {
+ Err(QueryExecutionError::DatabaseError.into())
+ }
+ }
+}
+
+impl OpenSearchIndexes {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+
+ when(self.payment_attempts.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Payment Attempts index must not be empty".into(),
+ ))
+ })?;
+
+ when(self.payment_intents.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Payment Intents index must not be empty".into(),
+ ))
+ })?;
+
+ when(self.refunds.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Refunds index must not be empty".into(),
+ ))
+ })?;
+
+ when(self.disputes.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Disputes index must not be empty".into(),
+ ))
+ })?;
+
+ Ok(())
+ }
+}
+
+impl OpenSearchAuth {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+
+ match self {
+ Self::Basic { username, password } => {
+ when(username.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Basic auth username must not be empty".into(),
+ ))
+ })?;
+
+ when(password.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Basic auth password must not be empty".into(),
+ ))
+ })?;
+ }
+
+ Self::Aws { region } => {
+ when(region.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Aws auth region must not be empty".into(),
+ ))
+ })?;
+ }
+ };
+
+ Ok(())
+ }
+}
+
+impl OpenSearchConfig {
+ pub async fn get_opensearch_client(&self) -> StorageResult<OpenSearchClient> {
+ Ok(OpenSearchClient::create(self)
+ .await
+ .map_err(|_| StorageError::InitializationError)?)
+ }
+
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+
+ when(self.host.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch host must not be empty".into(),
+ ))
+ })?;
+
+ self.indexes.validate()?;
+
+ self.auth.validate()?;
+
+ Ok(())
+ }
+}
+#[derive(Debug, serde::Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum OpenSearchHealthStatus {
+ Red,
+ Green,
+ Yellow,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpenSearchHealth {
+ pub status: OpenSearchHealthStatus,
+}
+
+#[derive(Debug, Clone)]
+pub enum OpenSearchQuery {
+ Msearch,
+ Search(SearchIndex),
+}
+
+#[derive(Debug, Clone)]
+pub struct OpenSearchQueryBuilder {
+ pub query_type: OpenSearchQuery,
+ pub query: String,
+ pub offset: Option<i64>,
+ pub count: Option<i64>,
+ pub filters: Vec<(String, String)>,
+}
+
+impl OpenSearchQueryBuilder {
+ pub fn new(query_type: OpenSearchQuery, query: String) -> Self {
+ Self {
+ query_type,
+ query,
+ offset: Default::default(),
+ count: Default::default(),
+ filters: Default::default(),
+ }
+ }
+
+ pub fn set_offset_n_count(&mut self, offset: i64, count: i64) -> QueryResult<()> {
+ self.offset = Some(offset);
+ self.count = Some(count);
+ Ok(())
+ }
+
+ pub fn add_filter_clause(&mut self, lhs: String, rhs: String) -> QueryResult<()> {
+ self.filters.push((lhs, rhs));
+ Ok(())
+ }
+
+ pub fn construct_payload(&self, indexes: Vec<SearchIndex>) -> QueryResult<Vec<Value>> {
+ let mut query =
+ vec![json!({"multi_match": {"type": "phrase", "query": self.query, "lenient": true}})];
+
+ let mut filters = self
+ .filters
+ .iter()
+ .map(|(k, v)| json!({"match_phrase" : {k : v}}))
+ .collect::<Vec<Value>>();
+
+ query.append(&mut filters);
+
+ // TODO add index specific filters
+ Ok(indexes
+ .iter()
+ .map(|_index| json!({"query": {"bool": {"filter": query}}}))
+ .collect::<Vec<Value>>())
+ }
+}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index 4c42e96250b..dc802ff6948 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -2,99 +2,33 @@ use api_models::analytics::search::{
GetGlobalSearchRequest, GetSearchRequestWithIndex, GetSearchResponse, OpenMsearchOutput,
OpensearchOutput, SearchIndex,
};
-use aws_config::{self, meta::region::RegionProviderChain, Region};
-use common_utils::errors::CustomResult;
-use opensearch::{
- auth::Credentials,
- cert::CertificateValidation,
- http::{
- request::JsonBody,
- transport::{SingleNodeConnectionPool, TransportBuilder},
- Url,
- },
- MsearchParts, OpenSearch, SearchParts,
-};
-use serde_json::{json, Value};
+use common_utils::errors::{CustomResult, ReportSwitchExt};
+use error_stack::ResultExt;
+use serde_json::Value;
use strum::IntoEnumIterator;
-use crate::{errors::AnalyticsError, OpensearchAuth, OpensearchConfig, OpensearchIndexes};
-
-#[derive(Debug, thiserror::Error)]
-pub enum OpensearchError {
- #[error("Opensearch connection error")]
- ConnectionError,
- #[error("Opensearch NON-200 response content: '{0}'")]
- ResponseNotOK(String),
- #[error("Opensearch response error")]
- ResponseError,
-}
-
-pub fn search_index_to_opensearch_index(index: SearchIndex, config: &OpensearchIndexes) -> String {
- match index {
- SearchIndex::PaymentAttempts => config.payment_attempts.clone(),
- SearchIndex::PaymentIntents => config.payment_intents.clone(),
- SearchIndex::Refunds => config.refunds.clone(),
- SearchIndex::Disputes => config.disputes.clone(),
- }
-}
-
-async fn get_opensearch_client(config: OpensearchConfig) -> Result<OpenSearch, OpensearchError> {
- let url = Url::parse(&config.host).map_err(|_| OpensearchError::ConnectionError)?;
- let transport = match config.auth {
- OpensearchAuth::Basic { username, password } => {
- let credentials = Credentials::Basic(username, password);
- TransportBuilder::new(SingleNodeConnectionPool::new(url))
- .cert_validation(CertificateValidation::None)
- .auth(credentials)
- .build()
- .map_err(|_| OpensearchError::ConnectionError)?
- }
- OpensearchAuth::Aws { region } => {
- let region_provider = RegionProviderChain::first_try(Region::new(region));
- let sdk_config = aws_config::from_env().region(region_provider).load().await;
- let conn_pool = SingleNodeConnectionPool::new(url);
- TransportBuilder::new(conn_pool)
- .auth(
- sdk_config
- .clone()
- .try_into()
- .map_err(|_| OpensearchError::ConnectionError)?,
- )
- .service_name("es")
- .build()
- .map_err(|_| OpensearchError::ConnectionError)?
- }
- };
- Ok(OpenSearch::new(transport))
-}
+use crate::opensearch::{
+ OpenSearchClient, OpenSearchError, OpenSearchQuery, OpenSearchQueryBuilder,
+};
pub async fn msearch_results(
+ client: &OpenSearchClient,
req: GetGlobalSearchRequest,
merchant_id: &String,
- config: OpensearchConfig,
-) -> CustomResult<Vec<GetSearchResponse>, AnalyticsError> {
- let client = get_opensearch_client(config.clone())
- .await
- .map_err(|_| AnalyticsError::UnknownError)?;
+) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> {
+ let mut query_builder = OpenSearchQueryBuilder::new(OpenSearchQuery::Msearch, req.query);
- let mut msearch_vector: Vec<JsonBody<Value>> = vec![];
- for index in SearchIndex::iter() {
- msearch_vector
- .push(json!({"index": search_index_to_opensearch_index(index,&config.indexes)}).into());
- msearch_vector.push(json!({"query": {"bool": {"filter": [{"multi_match": {"type": "phrase", "query": req.query, "lenient": true}},{"match_phrase": {"merchant_id": merchant_id}}]}}}).into());
- }
+ query_builder
+ .add_filter_clause("merchant_id".to_string(), merchant_id.to_string())
+ .switch()?;
- let response = client
- .msearch(MsearchParts::None)
- .body(msearch_vector)
- .send()
+ let response_body = client
+ .execute(query_builder)
.await
- .map_err(|_| AnalyticsError::UnknownError)?;
-
- let response_body = response
+ .change_context(OpenSearchError::ConnectionError)?
.json::<OpenMsearchOutput<Value>>()
.await
- .map_err(|_| AnalyticsError::UnknownError)?;
+ .change_context(OpenSearchError::ResponseError)?;
Ok(response_body
.responses
@@ -114,29 +48,30 @@ pub async fn msearch_results(
}
pub async fn search_results(
+ client: &OpenSearchClient,
req: GetSearchRequestWithIndex,
merchant_id: &String,
- config: OpensearchConfig,
-) -> CustomResult<GetSearchResponse, AnalyticsError> {
+) -> CustomResult<GetSearchResponse, OpenSearchError> {
let search_req = req.search_req;
- let client = get_opensearch_client(config.clone())
- .await
- .map_err(|_| AnalyticsError::UnknownError)?;
+ let mut query_builder =
+ OpenSearchQueryBuilder::new(OpenSearchQuery::Search(req.index), search_req.query);
- let response = client
- .search(SearchParts::Index(&[&search_index_to_opensearch_index(req.index.clone(),&config.indexes)]))
- .from(search_req.offset)
- .size(search_req.count)
- .body(json!({"query": {"bool": {"filter": [{"multi_match": {"type": "phrase", "query": search_req.query, "lenient": true}},{"match_phrase": {"merchant_id": merchant_id}}]}}}))
- .send()
- .await
- .map_err(|_| AnalyticsError::UnknownError)?;
+ query_builder
+ .add_filter_clause("merchant_id".to_string(), merchant_id.to_string())
+ .switch()?;
+
+ query_builder
+ .set_offset_n_count(search_req.offset, search_req.count)
+ .switch()?;
- let response_body = response
+ let response_body = client
+ .execute(query_builder)
+ .await
+ .change_context(OpenSearchError::ConnectionError)?
.json::<OpensearchOutput<Value>>()
.await
- .map_err(|_| AnalyticsError::UnknownError)?;
+ .change_context(OpenSearchError::ResponseError)?;
Ok(GetSearchResponse {
count: response_body.hits.total.value,
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index 3a5b3c307e6..6f6a3f22812 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -30,7 +30,7 @@ pub struct GetSearchRequestWithIndex {
pub search_req: GetSearchRequest,
}
-#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize)]
+#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)]
#[serde(rename_all = "snake_case")]
pub enum SearchIndex {
PaymentAttempts,
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs
index 29a59df397e..1e86e2964c7 100644
--- a/crates/api_models/src/health_check.rs
+++ b/crates/api_models/src/health_check.rs
@@ -6,6 +6,8 @@ pub struct RouterHealthCheckResponse {
pub vault: Option<bool>,
#[cfg(feature = "olap")]
pub analytics: bool,
+ #[cfg(feature = "olap")]
+ pub opensearch: bool,
pub outgoing_request: bool,
}
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 0aec94c205c..d509cf03d3c 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -614,9 +614,9 @@ pub mod routes {
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
analytics::search::msearch_results(
+ &state.opensearch_client,
req,
&auth.merchant_account.merchant_id,
- state.conf.opensearch.clone(),
)
.await
.map(ApplicationResponse::Json)
@@ -645,9 +645,9 @@ pub mod routes {
indexed_req,
|state, auth: AuthenticationData, req, _| async move {
analytics::search::search_results(
+ &state.opensearch_client,
req,
&auth.merchant_account.merchant_id,
- state.conf.opensearch.clone(),
)
.await
.map(ApplicationResponse::Json)
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 810ab5b98ed..01b05c60bd9 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -4,7 +4,7 @@ use std::{
};
#[cfg(feature = "olap")]
-use analytics::{OpensearchConfig, ReportConfig};
+use analytics::{opensearch::OpenSearchConfig, ReportConfig};
use api_models::{enums, payment_methods::RequiredFieldInfo};
use common_utils::ext_traits::ConfigExt;
use config::{Environment, File};
@@ -114,7 +114,7 @@ pub struct Settings<S: SecretState> {
#[cfg(feature = "olap")]
pub report_download_config: ReportConfig,
#[cfg(feature = "olap")]
- pub opensearch: OpensearchConfig,
+ pub opensearch: OpenSearchConfig,
pub events: EventsConfig,
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
@@ -730,6 +730,9 @@ impl Settings<SecuredSecret> {
self.lock_settings.validate()?;
self.events.validate()?;
+ #[cfg(feature = "olap")]
+ self.opensearch.validate()?;
+
self.encryption_management
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs
index 9997c6261fd..e90fe77e808 100644
--- a/crates/router/src/core/health_check.rs
+++ b/crates/router/src/core/health_check.rs
@@ -23,6 +23,11 @@ pub trait HealthCheckInterface {
#[cfg(feature = "olap")]
async fn health_check_analytics(&self)
-> CustomResult<HealthState, errors::HealthCheckDBError>;
+
+ #[cfg(feature = "olap")]
+ async fn health_check_opensearch(
+ &self,
+ ) -> CustomResult<HealthState, errors::HealthCheckDBError>;
}
#[async_trait::async_trait]
@@ -122,6 +127,18 @@ impl HealthCheckInterface for app::AppState {
Ok(HealthState::Running)
}
+ #[cfg(feature = "olap")]
+ async fn health_check_opensearch(
+ &self,
+ ) -> CustomResult<HealthState, errors::HealthCheckDBError> {
+ self.opensearch_client
+ .deep_health_check()
+ .await
+ .change_context(errors::HealthCheckDBError::OpensearchError)?;
+
+ Ok(HealthState::Running)
+ }
+
async fn health_check_outgoing(
&self,
) -> CustomResult<HealthState, errors::HealthCheckOutGoing> {
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ff660dbf7b7..543c703f1ca 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -41,6 +41,8 @@ use super::{currency, payment_methods::*};
use super::{ephemeral_key::*, webhooks::*};
#[cfg(feature = "oltp")]
use super::{pm_auth, poll::retrieve_poll_status};
+#[cfg(feature = "olap")]
+pub use crate::analytics::opensearch::OpenSearchClient;
use crate::configs::secrets_transformers;
#[cfg(all(feature = "frm", feature = "oltp"))]
use crate::routes::fraud_check as frm_routes;
@@ -73,6 +75,8 @@ pub struct AppState {
pub api_client: Box<dyn crate::services::ApiClient>,
#[cfg(feature = "olap")]
pub pool: crate::analytics::AnalyticsProvider,
+ #[cfg(feature = "olap")]
+ pub opensearch_client: OpenSearchClient,
pub request_id: Option<RequestId>,
pub file_storage_client: Box<dyn FileStorageInterface>,
pub encryption_client: Box<dyn EncryptionManagementInterface>,
@@ -177,6 +181,14 @@ impl AppState {
.await
.expect("Failed to create event handler");
+ #[allow(clippy::expect_used)]
+ #[cfg(feature = "olap")]
+ let opensearch_client = conf
+ .opensearch
+ .get_opensearch_client()
+ .await
+ .expect("Failed to create opensearch client");
+
let store: Box<dyn StorageInterface> = match storage_impl {
StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match &event_handler {
EventsHandler::Kafka(kafka_client) => Box::new(
@@ -223,6 +235,8 @@ impl AppState {
event_handler,
#[cfg(feature = "olap")]
pool,
+ #[cfg(feature = "olap")]
+ opensearch_client,
request_id: None,
file_storage_client,
encryption_client,
diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs
index fbfcd893a63..7d35a91a31e 100644
--- a/crates/router/src/routes/health.rs
+++ b/crates/router/src/routes/health.rs
@@ -74,6 +74,10 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
})
})?;
+ logger::debug!("Locker health check end");
+
+ logger::debug!("Analytics health check begin");
+
#[cfg(feature = "olap")]
let analytics_status = state.health_check_analytics().await.map_err(|err| {
error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
@@ -82,6 +86,22 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
})
})?;
+ logger::debug!("Analytics health check end");
+
+ logger::debug!("Opensearch health check begin");
+
+ #[cfg(feature = "olap")]
+ let opensearch_status = state.health_check_opensearch().await.map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Opensearch",
+ message: err.to_string()
+ })
+ })?;
+
+ logger::debug!("Opensearch health check end");
+
+ logger::debug!("Outgoing Request health check begin");
+
let outgoing_check = state.health_check_outgoing().await.map_err(|err| {
error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
@@ -89,7 +109,7 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
})
})?;
- logger::debug!("Locker health check end");
+ logger::debug!("Outgoing Request health check end");
let response = RouterHealthCheckResponse {
database: db_status.into(),
@@ -97,6 +117,8 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
vault: locker_status.into(),
#[cfg(feature = "olap")]
analytics: analytics_status.into(),
+ #[cfg(feature = "olap")]
+ opensearch: opensearch_status.into(),
outgoing_request: outgoing_check.into(),
};
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 4c5f84f5b73..8210b29a7cf 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -369,6 +369,8 @@ pub enum HealthCheckDBError {
SqlxAnalyticsError,
#[error("Error while executing query in Clickhouse Analytics")]
ClickhouseAnalyticsError,
+ #[error("Error while executing query in Opensearch")]
+ OpensearchError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
diff --git a/docker-compose.yml b/docker-compose.yml
index e55008f1e34..040832f8e27 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -332,4 +332,35 @@ services:
ulimits:
nofile:
soft: 262144
- hard: 262144
\ No newline at end of file
+ hard: 262144
+
+ fluentd:
+ build: ./docker/fluentd
+ volumes:
+ - ./docker/fluentd/conf:/fluentd/etc
+ networks:
+ - router_net
+
+ opensearch:
+ image: public.ecr.aws/opensearchproject/opensearch:1.3.14
+ container_name: opensearch
+ hostname: opensearch
+ environment:
+ - "discovery.type=single-node"
+ expose:
+ - "9200"
+ ports:
+ - "9200:9200"
+ networks:
+ - router_net
+
+ opensearch-dashboards:
+ image: opensearchproject/opensearch-dashboards:1.3.14
+ ports:
+ - 5601:5601
+ expose:
+ - "5601"
+ environment:
+ OPENSEARCH_HOSTS: '["https://opensearch:9200"]'
+ networks:
+ - router_net
\ No newline at end of file
diff --git a/docker/fluentd/Dockerfile b/docker/fluentd/Dockerfile
new file mode 100644
index 00000000000..5c85269e1a6
--- /dev/null
+++ b/docker/fluentd/Dockerfile
@@ -0,0 +1,7 @@
+# docker/fluentd/Dockerfile
+
+FROM fluent/fluentd:v1.16-debian-2
+USER root
+RUN ["gem", "install", "fluent-plugin-kafka", "--no-document"]
+RUN ["gem", "install", "fluent-plugin-opensearch", "--no-document"]
+USER fluent
diff --git a/docker/fluentd/conf/fluent.conf b/docker/fluentd/conf/fluent.conf
new file mode 100644
index 00000000000..7aec9dd7cd8
--- /dev/null
+++ b/docker/fluentd/conf/fluent.conf
@@ -0,0 +1,137 @@
+# docker/fluentd/conf/fluent.conf
+
+<source>
+ @type kafka_group
+
+ brokers kafka0:29092
+ consumer_group fluentd
+ topics hyperswitch-payment-intent-events,hyperswitch-payment-attempt-events,hyperswitch-refund-events,hyperswitch-dispute-events
+ add_headers false
+ add_prefix topic
+ retry_emit_limit 2
+</source>
+
+<filter topic.hyperswitch-payment-intent-events*>
+ @type record_transformer
+ renew_time_key created_at
+</filter>
+
+<filter topic.hyperswitch-payment-attempt-events*>
+ @type record_transformer
+ renew_time_key created_at
+</filter>
+
+<filter topic.hyperswitch-refund-events*>
+ @type record_transformer
+ renew_time_key created_at
+</filter>
+
+
+<filter topic.hyperswitch-dispute-events*>
+ @type record_transformer
+ renew_time_key created_at
+</filter>
+
+<match topic.hyperswitch-payment-intent-events*>
+ @type copy
+
+ <store>
+ @type stdout
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name hyperswitch-payment-intent-events
+ id_key payment_id
+ user admin
+ password admin
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+</match>
+
+<match topic.hyperswitch-payment-attempt-events*>
+ @type copy
+
+ <store>
+ @type stdout
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name hyperswitch-payment-attempt-events
+ id_key attempt_id
+ user admin
+ password admin
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+</match>
+
+<match topic.hyperswitch-refund-events*>
+ @type copy
+
+ <store>
+ @type stdout
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name hyperswitch-refund-events
+ id_key refund_id
+ user admin
+ password admin
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+</match>
+
+<match topic.hyperswitch-dispute-events*>
+ @type copy
+
+ <store>
+ @type stdout
+ </store>
+
+ <store>
+ @type opensearch
+ host opensearch
+ port 9200
+ scheme https
+ index_name hyperswitch-dispute-events
+ id_key dispute_id
+ user admin
+ password admin
+ ssl_verify false
+ prefer_oj_serializer true
+ reload_on_failure true
+ reload_connections false
+ request_timeout 120s
+ bulk_message_request_threshold 10MB
+ include_timestamp true
+ </store>
+</match>
\ No newline at end of file
|
2024-03-28T08:29:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
refactoring opensearch to module structure
### 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
refactoring
## How did you test it?
test cases added below
(verify sanity of all global search endpoints)
## Checklist
<!-- Put an `x` in 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
|
9bf16b1a0787f9badb4a6decd38e3e5d69a3ea51
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4214
|
Bug: [Patch]: Remove processing state from payment_method_status
This will remove the `processing` status from `payment_method_status` and by default makes everything active or failure.
This is a patch to ensure that no payment_method goes to non-terminal.
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 89ca80e72b3..17f0326a84d 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1252,7 +1252,6 @@ pub enum PaymentMethodStatus {
impl From<AttemptStatus> for PaymentMethodStatus {
fn from(attempt_status: AttemptStatus) -> Self {
match attempt_status {
- AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active,
AttemptStatus::Failure => Self::Inactive,
AttemptStatus::Voided
| AttemptStatus::Started
@@ -1274,7 +1273,9 @@ impl From<AttemptStatus> for PaymentMethodStatus {
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::ConfirmationAwaited
- | AttemptStatus::DeviceDataCollectionPending => Self::Processing,
+ | AttemptStatus::DeviceDataCollectionPending
+ | AttemptStatus::Charged
+ | AttemptStatus::Authorized => Self::Active,
}
}
}
|
2024-03-26T16:10:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will remove the `processing` status from `payment_method_status` and by default makes everything active or failure.
This is a patch to ensure that no payment_method goes to non-terminal.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Sample curl:
### `Payment Create` with confirm as false:
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_eZdRVkfE8sbYE7JSzm2Tu0HAca0PHRY6u3JoSFBukHuxoYeXw7bgwr7Gy2DJn1kS' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "cus_v6LovN3Zs9k8QQ2UYcbi",
"business_country": "US",
"business_label": "default",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "40",
"card_holder_name": "John",
"card_cvc": "737"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
'
```
`Payment's Confirm` using token
```
curl --location 'http://127.0.0.1:8080/payments/pay_y5QhUc1Z5Y14FYOQ7qcm/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_xxxx' \
--data '{
"payment_token": "token_UCstChJwCzgeWKlPJijf",
"card_cvc": "123"
}'
```
Response should include these two fields
```
"payment_method_id": "pm_pzFcNslye3gZLxUlmDbg",
"payment_method_status": "active" (previously it was null)
```
The possible status and mappings are as follows:
```
AttemptStatus::Failure => Self::Inactive,
AttemptStatus::Voided
| AttemptStatus::Started
| AttemptStatus::Pending
| AttemptStatus::Unresolved
| AttemptStatus::CodInitiated
| AttemptStatus::Authorizing
| AttemptStatus::VoidInitiated
| AttemptStatus::AuthorizationFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthenticationPending
| AttemptStatus::CaptureInitiated
| AttemptStatus::CaptureFailed
| AttemptStatus::VoidFailed
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending
| AttemptStatus::Charged
| AttemptStatus::Authorized => Self::Active,
```
## Checklist
<!-- Put an `x` in 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
|
e8289f061d4735478cb1521de50f696d2412ad33
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4246
|
Bug: [FEATURE] : [Billwerk] Add Payment and Refund Flows
### Feature Description
Add all the payment flows for non-3ds cards:
Authorise, Capture, Void, Psync
And the refund flows:
Refund and Rsync
### Possible Implementation
Add all the payment flows for non-3ds cards:
Authorise, Capture, Void, Psync
And the refund flows:
Refund and Rsync
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/config/config.example.toml b/config/config.example.toml
index ee868beb092..c1ba88db019 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -171,6 +171,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
@@ -349,6 +350,7 @@ stax = { long_lived_token = true, payment_method = "card,bank_debit" }
square = { long_lived_token = false, payment_method = "card" }
braintree = { long_lived_token = false, payment_method = "card" }
gocardless = { long_lived_token = true, payment_method = "bank_debit" }
+billwerk = {long_lived_token = false, payment_method = "card"}
[temp_locker_enable_config]
stripe = { payment_method = "bank_transfer" }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 10776c76678..77040f79a4a 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -21,6 +21,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
@@ -292,6 +293,7 @@ payme = { long_lived_token = false, payment_method = "card" }
square = { long_lived_token = false, payment_method = "card" }
stax = { long_lived_token = true, payment_method = "card,bank_debit" }
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { list = "google_pay", type = "disable_only" } }
+billwerk = {long_lived_token = false, payment_method = "card"}
[webhooks]
outgoing_enabled = true
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index a6405e4a3b2..23df14862b9 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -25,6 +25,7 @@ authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://api.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://bitpay.com"
bluesnap.base_url = "https://ws.bluesnap.com/"
bluesnap.secondary_base_url = "https://pay.bluesnap.com/"
@@ -306,6 +307,7 @@ payme = { long_lived_token = false, payment_method = "card" }
square = { long_lived_token = false, payment_method = "card" }
stax = { long_lived_token = true, payment_method = "card,bank_debit" }
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { list = "google_pay", type = "disable_only" } }
+billwerk = {long_lived_token = false, payment_method = "card"}
[webhooks]
outgoing_enabled = true
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 035c90af378..8ae12dc54a6 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -25,6 +25,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
@@ -308,6 +309,7 @@ payme = { long_lived_token = false, payment_method = "card" }
square = { long_lived_token = false, payment_method = "card" }
stax = { long_lived_token = true, payment_method = "card,bank_debit" }
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { list = "google_pay", type = "disable_only" } }
+billwerk = {long_lived_token = false, payment_method = "card"}
[webhooks]
outgoing_enabled = true
diff --git a/config/development.toml b/config/development.toml
index 5c063acf2f7..8ba5c076071 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -167,6 +167,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
@@ -450,6 +451,7 @@ square = { long_lived_token = false, payment_method = "card" }
braintree = { long_lived_token = false, payment_method = "card" }
payme = { long_lived_token = false, payment_method = "card" }
gocardless = { long_lived_token = true, payment_method = "bank_debit" }
+billwerk = {long_lived_token = false, payment_method = "card"}
[temp_locker_enable_config]
stripe = { payment_method = "bank_transfer" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 0e034f2e145..eb32b47e3b4 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -105,6 +105,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
@@ -251,6 +252,7 @@ stax = { long_lived_token = true, payment_method = "card,bank_debit" }
square = { long_lived_token = false, payment_method = "card" }
braintree = { long_lived_token = false, payment_method = "card" }
gocardless = { long_lived_token = true, payment_method = "bank_debit" }
+billwerk = {long_lived_token = false, payment_method = "card"}
[temp_locker_enable_config]
stripe = { payment_method = "bank_transfer" }
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index b29377886d5..354dec29237 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -78,7 +78,7 @@ pub enum Connector {
Authorizedotnet,
Bambora,
Bankofamerica,
- // Billwerk, Added as template code for future usage
+ Billwerk,
Bitpay,
Bluesnap,
Boku,
@@ -166,7 +166,7 @@ impl Connector {
| Self::Authorizedotnet
| Self::Bambora
| Self::Bankofamerica
- // | Self::Billwerk Added as template code for future usage
+ | Self::Billwerk
| Self::Bitpay
| Self::Bluesnap
| Self::Boku
@@ -223,7 +223,7 @@ impl Connector {
| Self::Authorizedotnet
| Self::Bambora
| Self::Bankofamerica
- // | Self::Billwerk Added as template for future usage
+ | Self::Billwerk
| Self::Bitpay
| Self::Bluesnap
| Self::Boku
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 548e721f0d3..497f1f58729 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -115,7 +115,7 @@ pub enum RoutableConnectors {
Airwallex,
Authorizedotnet,
Bankofamerica,
- // Billwerk, Added as template code for future usage
+ Billwerk,
Bitpay,
Bambora,
Bluesnap,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 74317319f50..5a67847a9e5 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -228,7 +228,7 @@ impl ConnectorConfig {
Connector::Airwallex => Ok(connector_data.airwallex),
Connector::Authorizedotnet => Ok(connector_data.authorizedotnet),
Connector::Bankofamerica => Ok(connector_data.bankofamerica),
- // Connector::Billwerk => Ok(connector_data.billwerk), Added as template code for future usage
+ Connector::Billwerk => Ok(connector_data.billwerk),
Connector::Bitpay => Ok(connector_data.bitpay),
Connector::Bluesnap => Ok(connector_data.bluesnap),
Connector::Boku => Ok(connector_data.boku),
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 0e18bb33ed2..0233b916668 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -2587,4 +2587,45 @@ api_key="Api Key"
[threedsecureio.metadata]
mcc="MCC"
merchant_country_code="3 digit numeric country code"
-merchant_name="Name of the merchant"
\ No newline at end of file
+merchant_name="Name of the merchant"
+
+[billwerk]
+[[billwerk.credit]]
+ payment_method_type = "Mastercard"
+[[billwerk.credit]]
+ payment_method_type = "Visa"
+[[billwerk.credit]]
+ payment_method_type = "Interac"
+[[billwerk.credit]]
+ payment_method_type = "AmericanExpress"
+[[billwerk.credit]]
+ payment_method_type = "JCB"
+[[billwerk.credit]]
+ payment_method_type = "DinersClub"
+[[billwerk.credit]]
+ payment_method_type = "Discover"
+[[billwerk.credit]]
+ payment_method_type = "CartesBancaires"
+[[billwerk.credit]]
+ payment_method_type = "UnionPay"
+[[billwerk.debit]]
+ payment_method_type = "Mastercard"
+[[billwerk.debit]]
+ payment_method_type = "Visa"
+[[billwerk.debit]]
+ payment_method_type = "Interac"
+[[billwerk.debit]]
+ payment_method_type = "AmericanExpress"
+[[billwerk.debit]]
+ payment_method_type = "JCB"
+[[billwerk.debit]]
+ payment_method_type = "DinersClub"
+[[billwerk.debit]]
+ payment_method_type = "Discover"
+[[billwerk.debit]]
+ payment_method_type = "CartesBancaires"
+[[billwerk.debit]]
+ payment_method_type = "UnionPay"
+[billwerk.connector_auth.BodyKey]
+api_key="Private Api Key"
+key1="Public Api Key"
\ No newline at end of file
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 079ead7e4ce..58f9ccfa2c3 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1913,4 +1913,45 @@ terminal_uuid="Terminal UUID"
pay_wall_secret="Pay Wall Secret"
[zen.metadata.google_pay]
terminal_uuid="Terminal UUID"
-pay_wall_secret="Pay Wall Secret"
\ No newline at end of file
+pay_wall_secret="Pay Wall Secret"
+
+[billwerk]
+[[billwerk.credit]]
+ payment_method_type = "Mastercard"
+[[billwerk.credit]]
+ payment_method_type = "Visa"
+[[billwerk.credit]]
+ payment_method_type = "Interac"
+[[billwerk.credit]]
+ payment_method_type = "AmericanExpress"
+[[billwerk.credit]]
+ payment_method_type = "JCB"
+[[billwerk.credit]]
+ payment_method_type = "DinersClub"
+[[billwerk.credit]]
+ payment_method_type = "Discover"
+[[billwerk.credit]]
+ payment_method_type = "CartesBancaires"
+[[billwerk.credit]]
+ payment_method_type = "UnionPay"
+[[billwerk.debit]]
+ payment_method_type = "Mastercard"
+[[billwerk.debit]]
+ payment_method_type = "Visa"
+[[billwerk.debit]]
+ payment_method_type = "Interac"
+[[billwerk.debit]]
+ payment_method_type = "AmericanExpress"
+[[billwerk.debit]]
+ payment_method_type = "JCB"
+[[billwerk.debit]]
+ payment_method_type = "DinersClub"
+[[billwerk.debit]]
+ payment_method_type = "Discover"
+[[billwerk.debit]]
+ payment_method_type = "CartesBancaires"
+[[billwerk.debit]]
+ payment_method_type = "UnionPay"
+[billwerk.connector_auth.BodyKey]
+api_key="Private Api Key"
+key1="Public Api Key"
\ No newline at end of file
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index f484e914531..9103c548e65 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -2589,4 +2589,45 @@ api_key="Api Key"
[threedsecureio.metadata]
mcc="MCC"
merchant_country_code="3 digit numeric country code"
-merchant_name="Name of the merchant"
\ No newline at end of file
+merchant_name="Name of the merchant"
+
+[billwerk]
+[[billwerk.credit]]
+ payment_method_type = "Mastercard"
+[[billwerk.credit]]
+ payment_method_type = "Visa"
+[[billwerk.credit]]
+ payment_method_type = "Interac"
+[[billwerk.credit]]
+ payment_method_type = "AmericanExpress"
+[[billwerk.credit]]
+ payment_method_type = "JCB"
+[[billwerk.credit]]
+ payment_method_type = "DinersClub"
+[[billwerk.credit]]
+ payment_method_type = "Discover"
+[[billwerk.credit]]
+ payment_method_type = "CartesBancaires"
+[[billwerk.credit]]
+ payment_method_type = "UnionPay"
+[[billwerk.debit]]
+ payment_method_type = "Mastercard"
+[[billwerk.debit]]
+ payment_method_type = "Visa"
+[[billwerk.debit]]
+ payment_method_type = "Interac"
+[[billwerk.debit]]
+ payment_method_type = "AmericanExpress"
+[[billwerk.debit]]
+ payment_method_type = "JCB"
+[[billwerk.debit]]
+ payment_method_type = "DinersClub"
+[[billwerk.debit]]
+ payment_method_type = "Discover"
+[[billwerk.debit]]
+ payment_method_type = "CartesBancaires"
+[[billwerk.debit]]
+ payment_method_type = "UnionPay"
+[billwerk.connector_auth.BodyKey]
+api_key="Private Api Key"
+key1="Public Api Key"
diff --git a/crates/router/src/connector/billwerk.rs b/crates/router/src/connector/billwerk.rs
index 154b729abc9..b6839f5de24 100644
--- a/crates/router/src/connector/billwerk.rs
+++ b/crates/router/src/connector/billwerk.rs
@@ -2,12 +2,15 @@ pub mod transformers;
use std::fmt::Debug;
+use base64::Engine;
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+use masking::PeekInterface;
use transformers as billwerk;
+use super::utils::RefundsRequestData;
use crate::{
configs::settings,
+ consts,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
@@ -40,16 +43,6 @@ impl api::RefundExecute for Billwerk {}
impl api::RefundSync for Billwerk {}
impl api::PaymentToken for Billwerk {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Billwerk
-{
- // Not Implemented (R)
-}
-
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk
where
Self: ConnectorIntegration<Flow, Request, Response>,
@@ -92,9 +85,10 @@ impl ConnectorCommon for Billwerk {
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let auth = billwerk::BillwerkAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let encoded_api_key = consts::BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek()));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
+ format!("Basic {encoded_api_key}").into_masked(),
)])
}
@@ -113,9 +107,13 @@ impl ConnectorCommon for Billwerk {
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response
+ .code
+ .map_or(consts::NO_ERROR_CODE.to_string(), |code| code.to_string()),
+ message: response
+ .message
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: Some(response.error),
attempt_status: None,
connector_transaction_id: None,
})
@@ -123,7 +121,20 @@ impl ConnectorCommon for Billwerk {
}
impl ConnectorValidation for Billwerk {
- //TODO: implement functions when support enabled
+ fn validate_capture_method(
+ &self,
+ capture_method: Option<common_enums::CaptureMethod>,
+ _pmt: Option<common_enums::PaymentMethodType>,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let capture_method = capture_method.unwrap_or_default();
+ match capture_method {
+ common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::Manual => Ok(()),
+ common_enums::CaptureMethod::ManualMultiple
+ | common_enums::CaptureMethod::Scheduled => Err(
+ super::utils::construct_not_implemented_error_report(capture_method, self.id()),
+ ),
+ }
+ }
}
impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
@@ -146,6 +157,105 @@ impl
{
}
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Billwerk
+{
+ fn get_headers(
+ &self,
+ req: &types::TokenizationRouterData,
+ 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::TokenizationRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let base_url = connectors
+ .billwerk
+ .secondary_base_url
+ .as_ref()
+ .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
+ Ok(format!("{base_url}v1/token"))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::TokenizationRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = billwerk::BillwerkTokenRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::TokenizationRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::TokenizationType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::TokenizationType::get_headers(self, req, connectors)?)
+ .set_body(types::TokenizationType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
+ where
+ types::PaymentsResponseData: Clone,
+ {
+ let response: billwerk::BillwerkTokenResponse = res
+ .response
+ .parse_struct("BillwerkTokenResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
for Billwerk
{
@@ -164,9 +274,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!("{}v1/charge", self.base_url(connectors)))
}
fn get_request_body(
@@ -214,7 +324,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: billwerk::BillwerkPaymentsResponse = res
.response
- .parse_struct("Billwerk PaymentsAuthorizeResponse")
+ .parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -232,6 +342,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
@@ -251,10 +369,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())
+ Ok(format!(
+ "{}v1/charge/{}",
+ self.base_url(connectors),
+ req.connector_request_reference_id
+ ))
}
fn build_request(
@@ -280,7 +402,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: billwerk::BillwerkPaymentsResponse = res
.response
- .parse_struct("billwerk PaymentsSyncResponse")
+ .parse_struct("billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -298,6 +420,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
@@ -317,18 +447,29 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_transaction_id = &req.request.connector_transaction_id;
+ Ok(format!(
+ "{}v1/charge/{connector_transaction_id}/settle",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
&self,
- _req: &types::PaymentsCaptureRouterData,
+ req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let connector_router_data = billwerk::BillwerkRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let connector_req = billwerk::BillwerkCaptureRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -359,7 +500,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: billwerk::BillwerkPaymentsResponse = res
.response
- .parse_struct("Billwerk PaymentsCaptureResponse")
+ .parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -377,11 +518,92 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for Billwerk
{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ 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::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_transaction_id = &req.request.connector_transaction_id;
+ Ok(format!(
+ "{}v1/charge/{connector_transaction_id}/cancel",
+ self.base_url(connectors)
+ ))
+ }
+
+ 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)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: billwerk::BillwerkPaymentsResponse = res
+ .response
+ .parse_struct("Billwerk BillwerkPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
@@ -402,9 +624,9 @@ 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!("{}v1/refund", self.base_url(connectors)))
}
fn get_request_body(
@@ -467,6 +689,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Billwerk {
@@ -484,10 +714,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())
+ let refund_id = req.request.get_connector_refund_id()?;
+ Ok(format!(
+ "{}v1/refund/{refund_id}",
+ self.base_url(connectors)
+ ))
}
fn build_request(
@@ -534,6 +768,14 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs
index c6f025b7898..ffcd14bf05f 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/router/src/connector/billwerk/transformers.rs
@@ -1,15 +1,16 @@
-use masking::Secret;
+use common_utils::pii::{Email, SecretSerdeValue};
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData},
+ consts,
core::errors,
types::{self, api, storage::enums},
};
-//TODO: Fill the struct with respective fields
pub struct BillwerkRouterData<T> {
- pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: i64,
pub router_data: T,
}
@@ -30,7 +31,6 @@ impl<T>
T,
),
) -> Result<Self, Self::Error> {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
Ok(Self {
amount,
router_data: item,
@@ -38,89 +38,213 @@ impl<T>
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct BillwerkPaymentsRequest {
- amount: i64,
- card: BillwerkCard,
+pub struct BillwerkAuthType {
+ pub(super) api_key: Secret<String>,
+ pub(super) public_api_key: Secret<String>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct BillwerkCard {
+impl TryFrom<&types::ConnectorAuthType> for BillwerkAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ api_key: api_key.to_owned(),
+ public_api_key: key1.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum BillwerkTokenRequestIntent {
+ ChargeAndStore,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum BillwerkStrongAuthRule {
+ UseScaIfAvailableAuth,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BillwerkTokenRequest {
number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+ month: Secret<String>,
+ year: Secret<String>,
+ cvv: Secret<String>,
+ pkey: Secret<String>,
+ recurring: Option<bool>,
+ intent: Option<BillwerkTokenRequestIntent>,
+ strong_authentication_rule: Option<BillwerkStrongAuthRule>,
}
-impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest {
+impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- match item.router_data.request.payment_method_data.clone() {
- api::PaymentMethodData::Card(req_card) => {
- let card = BillwerkCard {
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
- };
+ fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data.clone() {
+ api::PaymentMethodData::Card(ccard) => {
+ let connector_auth = &item.connector_auth_type;
+ let auth_type = BillwerkAuthType::try_from(connector_auth)?;
Ok(Self {
- amount: item.amount.to_owned(),
- card,
+ number: ccard.card_number.clone(),
+ month: ccard.card_exp_month.clone(),
+ year: ccard.get_card_expiry_year_2_digit()?,
+ cvv: ccard.card_cvc,
+ pkey: auth_type.public_api_key,
+ recurring: None,
+ intent: None,
+ strong_authentication_rule: None,
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ api_models::payments::PaymentMethodData::Wallet(_)
+ | api_models::payments::PaymentMethodData::CardRedirect(_)
+ | api_models::payments::PaymentMethodData::PayLater(_)
+ | api_models::payments::PaymentMethodData::BankRedirect(_)
+ | api_models::payments::PaymentMethodData::BankDebit(_)
+ | api_models::payments::PaymentMethodData::BankTransfer(_)
+ | api_models::payments::PaymentMethodData::Crypto(_)
+ | api_models::payments::PaymentMethodData::MandatePayment
+ | api_models::payments::PaymentMethodData::Reward
+ | api_models::payments::PaymentMethodData::Upi(_)
+ | api_models::payments::PaymentMethodData::Voucher(_)
+ | api_models::payments::PaymentMethodData::GiftCard(_)
+ | api_models::payments::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("billwerk"),
+ )
+ .into())
+ }
}
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
-pub struct BillwerkAuthType {
- pub(super) api_key: Secret<String>,
+#[derive(Debug, Deserialize, Serialize)]
+pub struct BillwerkTokenResponse {
+ id: Secret<String>,
+ recurring: Option<bool>,
}
-impl TryFrom<&types::ConnectorAuthType> for BillwerkAuthType {
+impl<T>
+ TryFrom<
+ types::ResponseRouterData<
+ api::PaymentMethodToken,
+ BillwerkTokenResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<api::PaymentMethodToken, T, types::PaymentsResponseData>
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
+ fn try_from(
+ item: types::ResponseRouterData<
+ api::PaymentMethodToken,
+ BillwerkTokenResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::PaymentsResponseData::TokenizationResponse {
+ token: item.response.id.expose(),
}),
- _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
- }
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Serialize)]
+pub struct BillwerkCustomerObject {
+ handle: Option<String>,
+ email: Option<Email>,
+ address: Option<Secret<String>>,
+ address2: Option<Secret<String>>,
+ city: Option<String>,
+ country: Option<common_enums::CountryAlpha2>,
+ first_name: Option<Secret<String>>,
+ last_name: Option<Secret<String>>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct BillwerkPaymentsRequest {
+ handle: String,
+ amount: i64,
+ source: Secret<String>,
+ currency: common_enums::Currency,
+ customer: BillwerkCustomerObject,
+ metadata: Option<SecretSerdeValue>,
+ settle: bool,
+}
+
+impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ if item.router_data.is_three_ds() {
+ return Err(errors::ConnectorError::NotImplemented(
+ "Three_ds payments through Billwerk".to_string(),
+ )
+ .into());
+ };
+ let source = match item.router_data.get_payment_method_token()? {
+ types::PaymentMethodToken::Token(pm_token) => Ok(Secret::new(pm_token)),
+ _ => Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "payment_method_token",
+ }),
+ }?;
+ Ok(Self {
+ handle: item.router_data.connector_request_reference_id.clone(),
+ amount: item.amount,
+ source,
+ currency: item.router_data.request.currency,
+ customer: BillwerkCustomerObject {
+ handle: item.router_data.customer_id.clone(),
+ email: item.router_data.request.email.clone(),
+ address: item.router_data.get_optional_billing_line1(),
+ address2: item.router_data.get_optional_billing_line2(),
+ city: item.router_data.get_optional_billing_city(),
+ country: item.router_data.get_optional_billing_country(),
+ first_name: item.router_data.get_optional_billing_first_name(),
+ last_name: item.router_data.get_optional_billing_last_name(),
+ },
+ metadata: item.router_data.request.metadata.clone(),
+ settle: item.router_data.request.is_auto_capture()?,
+ })
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
-pub enum BillwerkPaymentStatus {
- Succeeded,
+pub enum BillwerkPaymentState {
+ Created,
+ Authorized,
+ Pending,
+ Settled,
Failed,
- #[default]
- Processing,
+ Cancelled,
}
-impl From<BillwerkPaymentStatus> for enums::AttemptStatus {
- fn from(item: BillwerkPaymentStatus) -> Self {
+impl From<BillwerkPaymentState> for enums::AttemptStatus {
+ fn from(item: BillwerkPaymentState) -> Self {
match item {
- BillwerkPaymentStatus::Succeeded => Self::Charged,
- BillwerkPaymentStatus::Failed => Self::Failure,
- BillwerkPaymentStatus::Processing => Self::Authorizing,
+ BillwerkPaymentState::Created | BillwerkPaymentState::Pending => Self::Pending,
+ BillwerkPaymentState::Authorized => Self::Authorized,
+ BillwerkPaymentState::Settled => Self::Charged,
+ BillwerkPaymentState::Failed => Self::Failure,
+ BillwerkPaymentState::Cancelled => Self::Voided,
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BillwerkPaymentsResponse {
- status: BillwerkPaymentStatus,
- id: String,
+ state: BillwerkPaymentState,
+ handle: String,
+ error: Option<String>,
+ error_state: Option<String>,
}
impl<F, T>
@@ -136,28 +260,65 @@ impl<F, T>
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
+ let error_response = if item.response.error.is_some() || item.response.error_state.is_some()
+ {
+ Some(types::ErrorResponse {
+ code: item
+ .response
+ .error_state
+ .clone()
+ .unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ message: item
+ .response
+ .error_state
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: item.response.error,
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(item.response.handle.clone()),
+ })
+ } else {
+ None
+ };
+ let payments_response = types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.handle.clone()),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.handle),
+ incremental_authorization_allowed: None,
+ };
Ok(Self {
- status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- }),
+ status: enums::AttemptStatus::from(item.response.state),
+ response: error_response.map_or_else(|| Ok(payments_response), Err),
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
+#[derive(Debug, Serialize)]
+pub struct BillwerkCaptureRequest {
+ amount: i64,
+}
+
+impl TryFrom<&BillwerkRouterData<&types::PaymentsCaptureRouterData>> for BillwerkCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BillwerkRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount,
+ })
+ }
+}
+
// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
+#[derive(Debug, Serialize)]
pub struct BillwerkRefundRequest {
+ pub invoice: String,
pub amount: i64,
+ pub text: Option<String>,
}
impl<F> TryFrom<&BillwerkRouterData<&types::RefundsRouterData<F>>> for BillwerkRefundRequest {
@@ -166,38 +327,36 @@ impl<F> TryFrom<&BillwerkRouterData<&types::RefundsRouterData<F>>> for BillwerkR
item: &BillwerkRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.amount.to_owned(),
+ amount: item.amount,
+ invoice: item.router_data.request.connector_transaction_id.clone(),
+ text: item.router_data.request.reason.clone(),
})
}
}
// Type definition for Refund Response
-
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum RefundState {
+ Refunded,
Failed,
- #[default]
Processing,
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
+impl From<RefundState> for enums::RefundStatus {
+ fn from(item: RefundState) -> Self {
match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
+ RefundState::Refunded => Self::Success,
+ RefundState::Failed => Self::Failure,
+ RefundState::Processing => Self::Pending,
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
- status: RefundStatus,
+ state: RefundState,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
@@ -210,7 +369,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status: enums::RefundStatus::from(item.response.state),
}),
..item.data
})
@@ -227,18 +386,16 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status: enums::RefundStatus::from(item.response.state),
}),
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Serialize, Deserialize)]
pub struct BillwerkErrorResponse {
- pub status_code: u16,
- pub code: String,
- pub message: String,
- pub reason: Option<String>,
+ pub code: Option<i32>,
+ pub error: String,
+ pub message: Option<String>,
}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 89b88243057..804ad3ef3d0 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -88,6 +88,14 @@ pub trait RouterData {
fn get_optional_billing(&self) -> Option<&api::Address>;
fn get_optional_shipping(&self) -> Option<&api::Address>;
+ fn get_optional_billing_line1(&self) -> Option<Secret<String>>;
+ fn get_optional_billing_line2(&self) -> Option<Secret<String>>;
+ fn get_optional_billing_city(&self) -> Option<String>;
+ fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>;
+ fn get_optional_billing_zip(&self) -> Option<Secret<String>>;
+ fn get_optional_billing_state(&self) -> Option<Secret<String>>;
+ fn get_optional_billing_first_name(&self) -> Option<Secret<String>>;
+ fn get_optional_billing_last_name(&self) -> Option<Secret<String>>;
}
pub trait PaymentResponseRouterData {
@@ -202,6 +210,94 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
.ok_or_else(missing_field_err("session_token"))
}
+ fn get_optional_billing_line1(&self) -> Option<Secret<String>> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.line1)
+ })
+ }
+
+ fn get_optional_billing_line2(&self) -> Option<Secret<String>> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.line2)
+ })
+ }
+
+ fn get_optional_billing_city(&self) -> Option<String> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.city)
+ })
+ }
+
+ fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.country)
+ })
+ }
+
+ fn get_optional_billing_zip(&self) -> Option<Secret<String>> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.zip)
+ })
+ }
+
+ fn get_optional_billing_state(&self) -> Option<Secret<String>> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.state)
+ })
+ }
+
+ fn get_optional_billing_first_name(&self) -> Option<Secret<String>> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.first_name)
+ })
+ }
+
+ fn get_optional_billing_last_name(&self) -> Option<Secret<String>> {
+ self.address
+ .get_payment_method_billing()
+ .and_then(|billing_address| {
+ billing_address
+ .clone()
+ .address
+ .and_then(|billing_address_details| billing_address_details.last_name)
+ })
+ }
+
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index f48227b926e..ab402f3a891 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1731,10 +1731,10 @@ pub(crate) fn validate_auth_and_metadata_type(
bankofamerica::transformers::BankOfAmericaAuthType::try_from(val)?;
Ok(())
}
- // api_enums::Connector::Billwerk => {
- // billwerk::transformers::BillwerkAuthType::try_from(val)?;
- // Ok(())
- // } Added as template code for future usage
+ api_enums::Connector::Billwerk => {
+ billwerk::transformers::BillwerkAuthType::try_from(val)?;
+ Ok(())
+ }
api_enums::Connector::Bitpay => {
bitpay::transformers::BitpayAuthType::try_from(val)?;
Ok(())
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 4b72c7ac2e6..b5a4d04c927 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -326,7 +326,7 @@ impl ConnectorData {
enums::Connector::Authorizedotnet => Ok(Box::new(&connector::Authorizedotnet)),
enums::Connector::Bambora => Ok(Box::new(&connector::Bambora)),
enums::Connector::Bankofamerica => Ok(Box::new(&connector::Bankofamerica)),
- // enums::Connector::Billwerk => Ok(Box::new(&connector::Billwerk)), Added as template code for future usage
+ enums::Connector::Billwerk => Ok(Box::new(&connector::Billwerk)),
enums::Connector::Bitpay => Ok(Box::new(&connector::Bitpay)),
enums::Connector::Bluesnap => Ok(Box::new(&connector::Bluesnap)),
enums::Connector::Boku => Ok(Box::new(&connector::Boku)),
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 8a53a58aabd..be3cec3c3d9 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -188,7 +188,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Authorizedotnet => Self::Authorizedotnet,
api_enums::Connector::Bambora => Self::Bambora,
api_enums::Connector::Bankofamerica => Self::Bankofamerica,
- // api_enums::Connector::Billwerk => Self::Billwerk, Added as template code for future usage
+ api_enums::Connector::Billwerk => Self::Billwerk,
api_enums::Connector::Bitpay => Self::Bitpay,
api_enums::Connector::Bluesnap => Self::Bluesnap,
api_enums::Connector::Boku => Self::Boku,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 9a9a7606ca1..72eb6f25559 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -72,6 +72,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
billwerk.base_url = "https://api.reepay.com/"
+billwerk.secondary_base_url = "https://card.reepay.com/"
bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
@@ -219,6 +220,7 @@ checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_
mollie = {long_lived_token = false, payment_method = "card"}
braintree = { long_lived_token = false, payment_method = "card" }
gocardless = {long_lived_token = true, payment_method = "bank_debit"}
+billwerk = {long_lived_token = false, payment_method = "card"}
[connector_customer]
connector_list = "gocardless,stax,stripe"
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index fa9c7435632..227bdd5a0b1 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -7067,6 +7067,7 @@
"authorizedotnet",
"bambora",
"bankofamerica",
+ "billwerk",
"bitpay",
"bluesnap",
"boku",
@@ -16805,6 +16806,7 @@
"airwallex",
"authorizedotnet",
"bankofamerica",
+ "billwerk",
"bitpay",
"bambora",
"bluesnap",
|
2024-03-28T10:43:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
implement all the basic flows for Billwerk (Reepay):
- [Authorise/Charge](https://optimize-docs.billwerk.com/reference/createcharge)
- [Capture](https://optimize-docs.billwerk.com/reference/settlecharge)
- [Void](https://optimize-docs.billwerk.com/reference/cancelcharge)
- [Payments Sync](https://optimize-docs.billwerk.com/reference/getcharge)
- [Refund](https://optimize-docs.billwerk.com/reference/createrefund)
- [Refunds Sync](https://optimize-docs.billwerk.com/reference/getrefund)
### 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`
-->
Add Secondary Base Url and tokenisation 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).
-->
#4246
## How did you test 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 all the basic (no-3DS) and error cases for above mentioned flows. Refer to this [link](https://optimize-docs.billwerk.com/reference/testing) for test cards, Visa and MasterCard are not enabled on this account.
- ### Create Automatic Charge
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_sLGOvjA9xpMI1LxK7CJ9wHVMdEkncSpHcT8LB5MwNmaA32bD8LTVMuWO9tXmyBjs' \
--header 'x-feature: router-custom' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 1337,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 1337,
"customer_id": "customerg1",
"email": "guest2@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "340000000000009",
"card_exp_month": "12",
"card_exp_year": "2099",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled":true,
"ip_address": "127.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"test": "ket"
}
}'
```
- ### Create Manual Charge
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_sLGOvjA9xpMI1LxK7CJ9wHVMdEkncSpHcT8LB5MwNmaA32bD8LTVMuWO9tXmyBjs' \
--header 'x-feature: router-custom' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 1337,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 1337,
"customer_id": "customerg1",
"email": "guest2@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "340000000000009",
"card_exp_month": "12",
"card_exp_year": "2099",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled":true,
"ip_address": "127.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"test": "ket"
}
}'
```
- ### Capture an authorised Payment
```
curl --location 'http://localhost:8080/payments/pay_8CO6aT7MPI3WAh2le81B/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sLGOvjA9xpMI1LxK7CJ9wHVMdEkncSpHcT8LB5MwNmaA32bD8LTVMuWO9tXmyBjs' \
--data '{
"amount_to_capture": 1006,
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
- Void an Authorised Payment
```
curl --location 'http://localhost:8080/payments/pay_JH4ZARpgdDBt4akRLGAR/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sLGOvjA9xpMI1LxK7CJ9wHVMdEkncSpHcT8LB5MwNmaA32bD8LTVMuWO9tXmyBjs' \
--data '{
"cancellation_reason": "TIMEOUT"
}'
```
- ### Refund a Payment
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sLGOvjA9xpMI1LxK7CJ9wHVMdEkncSpHcT8LB5MwNmaA32bD8LTVMuWO9tXmyBjs' \
--data '{
"payment_id": "pay_6NDVXkL2qRWXh0Gq443H",
"amount": 100,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
a843713126cea102064b342b6fc82429d89d758a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4210
|
Bug: [Analytics/Payouts] - add kafka events and clickhouse schema for payout analytics
add kafka events and clickhouse schema for payout analytics
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 074028c208a..0ed971c18bd 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -568,6 +568,7 @@ connector_logs_topic = "topic" # Kafka topic to be used for connector api
outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events
dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events
audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events
+payout_analytics_topic = "topic" # Kafka topic to be used for Payout events
# File storage configuration
[file_storage]
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 8472076dc0c..e0caafa7d72 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -80,6 +80,7 @@ connector_logs_topic = "topic" # Kafka topic to be used for connector api
outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events
dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events
audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events
+payout_analytics_topic = "topic" # Kafka topic to be used for Payout events
# File storage configuration
[file_storage]
diff --git a/config/development.toml b/config/development.toml
index 7aaec8cc3a2..974e5407a66 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -556,6 +556,7 @@ connector_logs_topic = "hyperswitch-connector-api-events"
outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events"
dispute_analytics_topic = "hyperswitch-dispute-events"
audit_events_topic = "hyperswitch-audit-events"
+payout_analytics_topic = "hyperswitch-payout-events"
[analytics]
source = "sqlx"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index eaa7e92e14b..b81b6676f44 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -406,6 +406,7 @@ connector_logs_topic = "hyperswitch-connector-api-events"
outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events"
dispute_analytics_topic = "hyperswitch-dispute-events"
audit_events_topic = "hyperswitch-audit-events"
+payout_analytics_topic = "hyperswitch-payout-events"
[analytics]
source = "sqlx"
diff --git a/crates/analytics/docs/clickhouse/scripts/payouts.sql b/crates/analytics/docs/clickhouse/scripts/payouts.sql
new file mode 100644
index 00000000000..0358c0e9375
--- /dev/null
+++ b/crates/analytics/docs/clickhouse/scripts/payouts.sql
@@ -0,0 +1,109 @@
+CREATE TABLE payout_queue (
+ `payout_id` String,
+ `merchant_id` String,
+ `customer_id` String,
+ `address_id` String,
+ `payout_type` LowCardinality(String),
+ `payout_method_id` Nullable(String),
+ `amount` UInt64,
+ `destination_currency` LowCardinality(String),
+ `source_currency` LowCardinality(String),
+ `description` Nullable(String),
+ `recurring` Bool,
+ `auto_fulfill` Bool,
+ `return_url` Nullable(String),
+ `entity_type` LowCardinality(String),
+ `metadata` Nullable(String),
+ `created_at` DateTime CODEC(T64, LZ4),
+ `last_modified_at` DateTime CODEC(T64, LZ4),
+ `attempt_count` UInt16,
+ `profile_id` String,
+ `status` LowCardinality(String),
+ `sign_flag` Int8
+) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
+kafka_topic_list = 'hyperswitch-payout-events',
+kafka_group_name = 'hyper-c1',
+kafka_format = 'JSONEachRow',
+kafka_handle_error_mode = 'stream';
+
+CREATE TABLE payout (
+ `payout_id` String,
+ `merchant_id` String,
+ `customer_id` String,
+ `address_id` String,
+ `payout_type` LowCardinality(String),
+ `payout_method_id` Nullable(String),
+ `amount` UInt64,
+ `destination_currency` LowCardinality(String),
+ `source_currency` LowCardinality(String),
+ `description` Nullable(String),
+ `recurring` Bool,
+ `auto_fulfill` Bool,
+ `return_url` Nullable(String),
+ `entity_type` LowCardinality(String),
+ `metadata` Nullable(String),
+ `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `last_modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `attempt_count` UInt16,
+ `profile_id` String,
+ `status` LowCardinality(String),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `sign_flag` Int8,
+ INDEX payoutTypeIndex payout_type TYPE bloom_filter GRANULARITY 1,
+ INDEX destinationCurrencyIndex destination_currency TYPE bloom_filter GRANULARITY 1,
+ INDEX sourceCurrencyIndex source_currency TYPE bloom_filter GRANULARITY 1,
+ INDEX entityTypeIndex entity_type TYPE bloom_filter GRANULARITY 1,
+ INDEX statusIndex status TYPE bloom_filter GRANULARITY 1
+) ENGINE = CollapsingMergeTree(sign_flag) PARTITION BY toStartOfDay(created_at)
+ORDER BY
+ (created_at, merchant_id, payout_id) TTL created_at + toIntervalMonth(6);
+
+CREATE MATERIALIZED VIEW kafka_parse_payout TO payout (
+ `payout_id` String,
+ `merchant_id` String,
+ `customer_id` String,
+ `address_id` String,
+ `payout_type` LowCardinality(String),
+ `payout_method_id` Nullable(String),
+ `amount` UInt64,
+ `destination_currency` LowCardinality(String),
+ `source_currency` LowCardinality(String),
+ `description` Nullable(String),
+ `recurring` Bool,
+ `auto_fulfill` Bool,
+ `return_url` Nullable(String),
+ `entity_type` LowCardinality(String),
+ `metadata` Nullable(String),
+ `created_at` DateTime64(3),
+ `last_modified_at` DateTime64(3),
+ `attempt_count` UInt16,
+ `profile_id` String,
+ `status` LowCardinality(String),
+ `inserted_at` DateTime64(3),
+ `sign_flag` Int8
+) AS
+SELECT
+ payout_id,
+ merchant_id,
+ customer_id,
+ address_id,
+ payout_type,
+ payout_method_id,
+ amount,
+ destination_currency,
+ source_currency,
+ description,
+ recurring,
+ auto_fulfill,
+ return_url,
+ entity_type,
+ metadata,
+ created_at,
+ last_modified_at,
+ attempt_count,
+ profile_id,
+ status,
+ now() as inserted_at,
+ sign_flag
+FROM
+ payout_queue;
\ No newline at end of file
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index dc8b9b791d4..427c66daa07 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1546,9 +1546,20 @@ impl PayoutsInterface for KafkaStore {
payout_update: storage::PayoutsUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Payouts, errors::DataStorageError> {
- self.diesel_store
+ let payout = self
+ .diesel_store
.update_payout(this, payout_update, storage_scheme)
+ .await?;
+
+ if let Err(er) = self
+ .kafka_producer
+ .log_payout(&payout, Some(this.clone()))
.await
+ {
+ logger::error!(message="Failed to add analytics entry for Payout {payout:?}", error_message=?er);
+ };
+
+ Ok(payout)
}
async fn insert_payout(
@@ -1556,9 +1567,16 @@ impl PayoutsInterface for KafkaStore {
payout: storage::PayoutsNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Payouts, errors::DataStorageError> {
- self.diesel_store
+ let payout = self
+ .diesel_store
.insert_payout(payout, storage_scheme)
- .await
+ .await?;
+
+ if let Err(er) = self.kafka_producer.log_payout(&payout, None).await {
+ logger::error!(message="Failed to add analytics entry for Payout {payout:?}", error_message=?er);
+ };
+
+ Ok(payout)
}
async fn find_optional_payout_by_merchant_id_payout_id(
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index 5f6d978d455..2a0944b2f26 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -26,6 +26,7 @@ pub enum EventType {
OutgoingWebhookLogs,
Dispute,
AuditEvent,
+ Payout,
}
#[derive(Debug, Default, Deserialize, Clone)]
@@ -39,6 +40,7 @@ pub enum EventsConfig {
Logs,
}
+#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum EventsHandler {
Kafka(KafkaProducer),
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 373c268f85b..e4708f86681 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -11,17 +11,23 @@ use crate::events::EventType;
mod dispute;
mod payment_attempt;
mod payment_intent;
+mod payout;
mod refund;
use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use diesel_models::refund::Refund;
use serde::Serialize;
use time::OffsetDateTime;
+#[cfg(feature = "payouts")]
+use self::payout::KafkaPayout;
use self::{
dispute::KafkaDispute, payment_attempt::KafkaPaymentAttempt,
payment_intent::KafkaPaymentIntent, refund::KafkaRefund,
};
use crate::types::storage::Dispute;
+#[cfg(feature = "payouts")]
+use crate::types::storage::Payouts;
+
// Using message queue result here to avoid confusion with Kafka result provided by library
pub type MQResult<T> = CustomResult<T, KafkaError>;
@@ -91,6 +97,7 @@ pub struct KafkaSettings {
outgoing_webhook_logs_topic: String,
dispute_analytics_topic: String,
audit_events_topic: String,
+ payout_analytics_topic: String,
}
impl KafkaSettings {
@@ -156,6 +163,12 @@ impl KafkaSettings {
))
})?;
+ common_utils::fp_utils::when(self.payout_analytics_topic.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Kafka Payout Analytics topic must not be empty".into(),
+ ))
+ })?;
+
Ok(())
}
}
@@ -171,6 +184,7 @@ pub struct KafkaProducer {
outgoing_webhook_logs_topic: String,
dispute_analytics_topic: String,
audit_events_topic: String,
+ payout_analytics_topic: String,
}
struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>);
@@ -210,6 +224,7 @@ impl KafkaProducer {
outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(),
dispute_analytics_topic: conf.dispute_analytics_topic.clone(),
audit_events_topic: conf.audit_events_topic.clone(),
+ payout_analytics_topic: conf.payout_analytics_topic.clone(),
})
}
@@ -224,6 +239,7 @@ impl KafkaProducer {
EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
EventType::Dispute => &self.dispute_analytics_topic,
EventType::AuditEvent => &self.audit_events_topic,
+ EventType::Payout => &self.payout_analytics_topic,
};
self.producer
.0
@@ -340,6 +356,30 @@ impl KafkaProducer {
.attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))
}
+ #[cfg(feature = "payouts")]
+ pub async fn log_payout(&self, payout: &Payouts, old_payout: Option<Payouts>) -> MQResult<()> {
+ if let Some(negative_event) = old_payout {
+ self.log_event(&KafkaEvent::old(&KafkaPayout::from_storage(
+ &negative_event,
+ )))
+ .attach_printable_lazy(|| {
+ format!("Failed to add negative payout event {negative_event:?}")
+ })?;
+ };
+ self.log_event(&KafkaEvent::new(&KafkaPayout::from_storage(payout)))
+ .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}"))
+ }
+
+ #[cfg(feature = "payouts")]
+ pub async fn log_payout_delete(&self, delete_old_payout: &Payouts) -> MQResult<()> {
+ self.log_event(&KafkaEvent::old(&KafkaPayout::from_storage(
+ delete_old_payout,
+ )))
+ .attach_printable_lazy(|| {
+ format!("Failed to add negative payout event {delete_old_payout:?}")
+ })
+ }
+
pub fn get_topic(&self, event: EventType) -> &str {
match event {
EventType::ApiLogs => &self.api_logs_topic,
@@ -350,6 +390,7 @@ impl KafkaProducer {
EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
EventType::Dispute => &self.dispute_analytics_topic,
EventType::AuditEvent => &self.audit_events_topic,
+ EventType::Payout => &self.payout_analytics_topic,
}
}
}
diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs
new file mode 100644
index 00000000000..7e181e3d1f6
--- /dev/null
+++ b/crates/router/src/services/kafka/payout.rs
@@ -0,0 +1,74 @@
+use common_utils::pii;
+use diesel_models::enums as storage_enums;
+use time::OffsetDateTime;
+
+#[cfg(feature = "payouts")]
+use crate::types::storage::Payouts;
+
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaPayout<'a> {
+ pub payout_id: &'a String,
+ pub merchant_id: &'a String,
+ pub customer_id: &'a String,
+ pub address_id: &'a String,
+ pub payout_type: &'a storage_enums::PayoutType,
+ pub payout_method_id: Option<&'a String>,
+ pub amount: i64,
+ pub destination_currency: &'a storage_enums::Currency,
+ pub source_currency: &'a storage_enums::Currency,
+ pub description: Option<&'a String>,
+ pub recurring: bool,
+ pub auto_fulfill: bool,
+ pub return_url: Option<&'a String>,
+ pub entity_type: &'a storage_enums::PayoutEntityType,
+ pub metadata: Option<&'a pii::SecretSerdeValue>,
+ #[serde(default, with = "time::serde::timestamp")]
+ pub created_at: OffsetDateTime,
+ #[serde(default, with = "time::serde::timestamp")]
+ pub last_modified_at: OffsetDateTime,
+ pub attempt_count: i16,
+ pub profile_id: &'a String,
+ pub status: &'a storage_enums::PayoutStatus,
+}
+
+#[cfg(feature = "payouts")]
+impl<'a> KafkaPayout<'a> {
+ pub fn from_storage(payout: &'a Payouts) -> Self {
+ Self {
+ payout_id: &payout.payout_id,
+ merchant_id: &payout.merchant_id,
+ customer_id: &payout.customer_id,
+ address_id: &payout.address_id,
+ payout_type: &payout.payout_type,
+ payout_method_id: payout.payout_method_id.as_ref(),
+ amount: payout.amount,
+ destination_currency: &payout.destination_currency,
+ source_currency: &payout.source_currency,
+ description: payout.description.as_ref(),
+ recurring: payout.recurring,
+ auto_fulfill: payout.auto_fulfill,
+ return_url: payout.return_url.as_ref(),
+ entity_type: &payout.entity_type,
+ metadata: payout.metadata.as_ref(),
+ created_at: payout.created_at.assume_utc(),
+ last_modified_at: payout.last_modified_at.assume_utc(),
+ attempt_count: payout.attempt_count,
+ profile_id: &payout.profile_id,
+ status: &payout.status,
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaPayout<'a> {
+ fn key(&self) -> String {
+ format!("{}_{}", self.merchant_id, self.payout_id)
+ }
+
+ fn creation_timestamp(&self) -> Option<i64> {
+ Some(self.last_modified_at.unix_timestamp())
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::Payout
+ }
+}
|
2024-03-26T14:45:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
add kafka events and clickhouse schema for payout analytics
### 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
add kafka events and clickhouse schema for payout analytics
closes [#4210](https://github.com/juspay/hyperswitch/issues/4210)
## How did you test it?
Create a payout -> check for logs in loki `topic: hyperswitch-payout-events`
test cases added below
## Checklist
<!-- Put an `x` in 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
|
1023f46c885dc2b70ccbb3931e667740695f448e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4235
|
Bug: add `merchant_business_country` field in apple pay `session_token_data`
Merchant business country is mandatory field for confirming a apple pay payment. Till date we were expecting the billing country to be passed in the apple pay payment create call. Instead of collecting it is every payment create call this can be collected in the apple pay metadata while enabling apple pay for a specific connector (merchant connector account).
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 6805363b265..097351882c1 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3799,11 +3799,15 @@ pub struct SessionTokenInfo {
pub display_name: String,
pub initiative: String,
pub initiative_context: String,
+ #[schema(value_type = Option<CountryAlpha2>)]
+ pub merchant_business_country: Option<api_enums::CountryAlpha2>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct SessionTokenForSimplifiedApplePay {
pub initiative_context: String,
+ #[schema(value_type = Option<CountryAlpha2>)]
+ pub merchant_business_country: Option<api_enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
@@ -3971,7 +3975,7 @@ pub struct SecretInfoToInitiateSdk {
pub struct ApplePayPaymentRequest {
/// The code for country
#[schema(value_type = CountryAlpha2, example = "US")]
- pub country_code: Option<api_enums::CountryAlpha2>,
+ pub country_code: api_enums::CountryAlpha2,
/// The code for currency
#[schema(value_type = Currency, example = "USD")]
pub currency_code: api_enums::Currency,
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 0233b916668..c3d9bc2be7b 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -246,6 +246,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -354,6 +355,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -414,6 +416,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bambora.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -474,6 +477,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -551,6 +555,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -775,6 +780,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -856,6 +862,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1271,6 +1278,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1337,6 +1345,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nmi.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1404,6 +1413,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[noon.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1483,6 +1493,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nuvei.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1790,6 +1801,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1944,6 +1956,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2101,6 +2114,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2268,6 +2282,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 58f9ccfa2c3..f431846666b 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -139,6 +139,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -248,6 +249,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -322,6 +324,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -433,6 +436,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bambora.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -494,6 +498,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -661,6 +666,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -731,6 +737,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1127,6 +1134,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1378,6 +1386,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1516,6 +1525,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1588,6 +1598,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1696,6 +1707,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 9103c548e65..6a1da5aff0a 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -246,6 +246,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -354,6 +355,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -414,6 +416,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bambora.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -474,6 +477,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -551,6 +555,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -775,6 +780,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -856,6 +862,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1271,6 +1278,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1337,6 +1345,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nmi.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1404,6 +1413,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[noon.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1483,6 +1493,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[nuvei.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1790,6 +1801,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1944,6 +1956,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2101,6 +2114,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2268,6 +2282,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+merchant_business_country="Merchant Business Country"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 362e1aed183..e92ba864775 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -550,7 +550,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons
session_response,
),
payment_request_data: Some(api_models::payments::ApplePayPaymentRequest {
- country_code: item.data.request.country,
+ country_code: item.data.get_billing_country()?,
currency_code: item.data.request.currency,
total: api_models::payments::AmountInfo {
label: payment_request_data.label,
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 0c284a3f8e7..7f5e30402d6 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -538,11 +538,6 @@ impl<F>
}
_ => {
let currency_code = item.data.request.get_currency()?;
- let country_code = item
- .data
- .get_optional_billing()
- .and_then(|billing| billing.address.as_ref())
- .and_then(|address| address.country);
let amount = item.data.request.get_amount()?;
let amount_in_base_unit = utils::to_currency_base_unit(amount, currency_code)?;
let pmd = item.data.request.payment_method_data.to_owned();
@@ -557,7 +552,7 @@ impl<F>
api_models::payments::ApplePaySessionResponse::NoSessionResponse,
payment_request_data: Some(
api_models::payments::ApplePayPaymentRequest {
- country_code,
+ country_code: item.data.get_billing_country()?,
currency_code,
total: api_models::payments::AmountInfo {
label: "Apple Pay".to_string(),
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index 79396f12c69..c40435c01bb 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -1222,7 +1222,7 @@ pub fn get_apple_pay_session<F, T>(
},
),
payment_request_data: Some(api_models::payments::ApplePayPaymentRequest {
- country_code: Some(apple_pay_init_result.country_code),
+ country_code: apple_pay_init_result.country_code,
currency_code: apple_pay_init_result.currency_code,
supported_networks: Some(apple_pay_init_result.supported_networks.clone()),
merchant_capabilities: Some(
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 1ab72dff15b..7e15e2ed3f9 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -169,6 +169,7 @@ async fn create_applepay_session_token(
apple_pay_session_request,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
+ merchant_business_country,
) = match apple_pay_metadata {
payment_types::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
@@ -185,6 +186,8 @@ async fn create_applepay_session_token(
.clone()
.expose();
+ let merchant_business_country = session_token_data.merchant_business_country;
+
let apple_pay_session_request = get_session_request_for_simplified_apple_pay(
merchant_identifier,
session_token_data,
@@ -211,6 +214,7 @@ async fn create_applepay_session_token(
apple_pay_session_request,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
+ merchant_business_country,
)
}
payment_types::ApplePayCombinedMetadata::Manual {
@@ -219,11 +223,15 @@ async fn create_applepay_session_token(
} => {
let apple_pay_session_request =
get_session_request_for_manual_apple_pay(session_token_data.clone());
+
+ let merchant_business_country = session_token_data.merchant_business_country;
+
(
payment_request_data,
apple_pay_session_request,
session_token_data.certificate.clone(),
session_token_data.certificate_keys,
+ merchant_business_country,
)
}
},
@@ -231,11 +239,16 @@ async fn create_applepay_session_token(
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
apple_pay_metadata.session_token_data.clone(),
);
+
+ let merchant_business_country = apple_pay_metadata
+ .session_token_data
+ .merchant_business_country;
(
apple_pay_metadata.payment_request_data,
apple_pay_session_request,
apple_pay_metadata.session_token_data.certificate.clone(),
apple_pay_metadata.session_token_data.certificate_keys,
+ merchant_business_country,
)
}
};
@@ -252,6 +265,7 @@ async fn create_applepay_session_token(
payment_request_data,
router_data.request.to_owned(),
apple_pay_session_request.merchant_identifier.as_str(),
+ merchant_business_country,
)?;
let applepay_session_request = build_apple_pay_session_request(
@@ -351,9 +365,14 @@ fn get_apple_pay_payment_request(
payment_request_data: payment_types::PaymentRequestMetadata,
session_data: types::PaymentsSessionData,
merchant_identifier: &str,
+ merchant_business_country: Option<api_models::enums::CountryAlpha2>,
) -> RouterResult<payment_types::ApplePayPaymentRequest> {
let applepay_payment_request = payment_types::ApplePayPaymentRequest {
- country_code: session_data.country,
+ country_code: merchant_business_country.or(session_data.country).ok_or(
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "country_code",
+ },
+ )?,
currency_code: session_data.currency,
total: amount_info,
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 1af82da7f59..709d9b0d6ca 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -17497,6 +17497,14 @@
},
"initiative_context": {
"type": "string"
+ },
+ "merchant_business_country": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ ],
+ "nullable": true
}
}
},
|
2024-03-27T13:54:29Z
|
## 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 -->
Merchant business country is mandatory field for confirming a apple pay payment. Till date we were expecting the billing country to be passed in the apple pay payment create call. Instead of collecting it is every payment create call this can be collected in the apple pay metadata while enabling apple pay for a specific connector (merchant connector account).
This pr also makes the billing country for apple pay as mandatory field (reverting the changes of https://github.com/juspay/hyperswitch/pull/3188). As `merchant_business_country` is a mandatory field for confirming an apple pay payment.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test 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 apple pay metadata as shown below
```
{
"connector_type": "fiz_operations",
"connector_name": "stripe",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "certificate",
"display_name": "applepay",
"certificate_keys": "certificate_keys",
"initiative_context": "initiative_context",
"merchant_identifier": "merchant_identifier",
"merchant_business_country": "merchant_business_country"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"google_pay": {
"merchant_info": {
"merchant_name": "Stripe"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": ""
}
}
}
]
}
}
}
```
Create a payment with confirm = false and without passing billing country
<img width="1070" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/eb3c3e4e-f7ec-4236-967c-3797490b6701">
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"payment_data",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "transaction_identifier"
}
}
}
}
```
<img width="1089" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ab750cb6-0ac7-4ce3-8363-5897b4a4d28f">
Make a session token call with the payment_id and the client_secret in the above payment create response
```
{
"payment_id": "{{payment_id}}",
"wallets": [],
"client_secret": "{{client_secret}}"
}
```
<img width="1087" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e27cbc55-66f5-4d30-ac50-2ac538788847">
## Checklist
<!-- Put an `x` in 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
|
433b4bbf278b95be6c3f1d5f4749cf765b664e80
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4276
|
Bug: [Refactor] fix typos
We use typos-cli crate to catch typos in the repo. A new version of the same was released and has caught few new typos in the repo.
|
diff --git a/.typos.toml b/.typos.toml
index 58e48220bd7..642eaded60e 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -3,44 +3,62 @@ check-filename = true
[default.extend-identifiers]
"ABD" = "ABD" # Aberdeenshire, UK ISO 3166-2 code
+AER = "AER" # An alias to Api Error Response
+ANG = "ANG" # Netherlands Antillean guilder currency code
BA = "BA" # Bosnia and Herzegovina country code
+bottm = "bottm" # name of a css class for nexinets ui test
CAF = "CAF" # Central African Republic country code
-flate2 = "flate2"
FO = "FO" # Faroe Islands (the) country code
+flate2 = "flate2"
+hd = "hd" # animation data parameter
HypoNoeLbFurNiederosterreichUWien = "HypoNoeLbFurNiederosterreichUWien"
hypo_noe_lb_fur_niederosterreich_u_wien = "hypo_noe_lb_fur_niederosterreich_u_wien"
+IOT = "IOT" # British Indian Ocean Territory country code
+klick = "klick" # Swedish word for clicks
+LSO = "LSO" # Lesotho country code
NAM = "NAM" # Namibia country code
ND = "ND" # North Dakota state code
+optin = "optin" # Boku preflow name
+optin_id = "optin_id" # Boku's id for optin flow
+passord = "passord" # name of a css class for adyen ui test
payment_vas = "payment_vas"
PaymentVas = "PaymentVas"
+PN = "PN" # Pitcairn country code
RegioBank = "RegioBank"
+RO = "RO" # Romania country code
+skip_ws = "skip_ws" # skip white space
SOM = "SOM" # Somalia country code
+SUR = "SUR" # Single South American currency code
THA = "THA" # Thailand country code
+TTO = "TTO" # Trinidad and Tobago country code
+WS = "WS" # Samoa country code
+ws = "ws" # Web socket
+ws2ipdef = "ws2ipdef" # WinSock Extension
+ws2tcpip = "ws2tcpip" # WinSock Extension
ZAR = "ZAR" # South African Rand currency code
-SUR = "SUR" # Single South American currency code
-passord = "passord" # name of a css class for adyen ui test
-bottm = "bottm" # name of a css class for nexinets ui test
-klick = "klick" # Swedish word for clicks
-optin = "optin" # Boku preflow name
-optin_id = "optin_id" # Boku's id for optin flow
+
[default.extend-words]
-aci = "aci" # Name of a connector
-encrypter = "encrypter" # Used by the `ring` crate
-nin = "nin" # National identification number, a field used by PayU connector
-substituters = "substituters" # Present in `flake.nix`
-unsuccess = "unsuccess" # Used in cryptopay request
+aci = "aci" # Name of a connector
+afe = "afe" # Commit id
ba = "ba" # ignore minor commit conversions
-ede = "ede" # ignore minor commit conversions
daa = "daa" # Commit id
-afe = "afe" # Commit id
+deriver = "deriver"
+ede = "ede" # ignore minor commit conversions
+encrypter = "encrypter" # Used by the `ring` crate
+guid = "guid" # globally unique identifier
Hashi = "Hashi" # HashiCorp
+iin = "iin" # Card iin
+kms = "kms" # Key management service
+nin = "nin" # National identification number, a field used by PayU connector
requestor = "requestor" #Used in external 3ds flows
-deriver = "deriver"
+substituters = "substituters" # Present in `flake.nix`
+unsuccess = "unsuccess" # Used in cryptopay request
[files]
extend-exclude = [
"config/redis.conf", # `typos` also checked "AKE" in the file, which is present as a quoted string
"openapi/open_api_spec.yaml", # no longer updated
"crates/router/src/utils/user/blocker_emails.txt", # this file contains various email domains
+ "CHANGELOG.md", # This file contains all the commits
]
diff --git a/INSTALL_dependencies.sh b/INSTALL_dependencies.sh
index 288dea1bd44..8f893f54459 100755
--- a/INSTALL_dependencies.sh
+++ b/INSTALL_dependencies.sh
@@ -67,8 +67,8 @@ need_cmd () {
}
prompt () {
- read -p "$*? [y/N] :" ANS
- case $ANS in
+ read -p "$*? [y/N] :" ANSWER
+ case $ANSWER in
[Yy]*) return 1;;
*) return 0;;
esac
diff --git a/connector-template/test.rs b/connector-template/test.rs
index 7b093ddb6ef..f408070fe3c 100644
--- a/connector-template/test.rs
+++ b/connector-template/test.rs
@@ -281,7 +281,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index f08a793ebf5..e7a0ddd1ef1 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -145,7 +145,7 @@ pub struct PaymentMethodResponse {
pub customer_id: Option<String>,
/// The unique identifier of the Payment method
- #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")]
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")]
pub payment_method_id: String,
/// The type of payment method use for the payment.
@@ -536,7 +536,7 @@ pub struct RequestPaymentMethodTypes {
#[serde(deny_unknown_fields)]
pub struct PaymentMethodListRequest {
/// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
- #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893ein2d")]
+ #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
pub client_secret: Option<String>,
/// The two-letter ISO currency code
@@ -743,7 +743,7 @@ pub struct CustomerPaymentMethodsListResponse {
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodDeleteResponse {
/// The unique identifier of the Payment method
- #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")]
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")]
pub payment_method_id: String,
/// Whether payment method was deleted or not
@@ -753,7 +753,7 @@ pub struct PaymentMethodDeleteResponse {
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct CustomerDefaultPaymentMethodResponse {
/// The unique identifier of the Payment method
- #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")]
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")]
pub default_payment_method_id: Option<String>,
/// The unique identifier of the customer.
#[schema(example = "cus_meowerunwiuwiwqw")]
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index 97182df0a5e..ea28ed56af3 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -9,7 +9,7 @@ use crate::{admin, enums};
#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RefundRequest {
- /// The payment id against which refund is to be intiated
+ /// The payment id against which refund is to be initiated
#[schema(
max_length = 30,
min_length = 30,
@@ -102,7 +102,7 @@ pub enum RefundType {
pub struct RefundResponse {
/// Unique Identifier for the refund
pub refund_id: String,
- /// The payment id against which refund is intiated
+ /// The payment id against which refund is initiated
pub payment_id: String,
/// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc
pub amount: i64,
diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs
index bd23ae38522..cb72cca0448 100644
--- a/crates/euclid/src/dssa/graph.rs
+++ b/crates/euclid/src/dssa/graph.rs
@@ -1465,7 +1465,7 @@ mod test {
]),
&mut memo,
);
- let _ans = memo
+ let _answer = memo
.0
.get(&(
_node_3.expect("node3 construction failed"),
@@ -1473,6 +1473,6 @@ mod test {
Strength::Strong,
))
.expect("Memoization not workng");
- matches!(_ans, Ok(()));
+ matches!(_answer, Ok(()));
}
}
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 5a26c5e2615..404d0e93db7 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -423,8 +423,9 @@ impl From<api_enums::IntentStatus> for StripePaymentStatus {
}
}
-#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
+#[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)]
#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
pub enum CancellationReason {
Duplicate,
Fraudulent,
@@ -432,17 +433,6 @@ pub enum CancellationReason {
Abandoned,
}
-impl ToString for CancellationReason {
- fn to_string(&self) -> String {
- String::from(match self {
- Self::Duplicate => "duplicate",
- Self::Fraudulent => "fradulent",
- Self::RequestedByCustomer => "requested_by_customer",
- Self::Abandoned => "abandoned",
- })
- }
-}
-
#[derive(Debug, Deserialize, Serialize, Copy, Clone)]
pub struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>,
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index 6fb6b6c808b..d29bf235b57 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -334,8 +334,9 @@ impl From<api_enums::IntentStatus> for StripeSetupStatus {
}
}
-#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
+#[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)]
#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
pub enum CancellationReason {
Duplicate,
Fraudulent,
@@ -343,17 +344,6 @@ pub enum CancellationReason {
Abandoned,
}
-impl ToString for CancellationReason {
- fn to_string(&self) -> String {
- String::from(match self {
- Self::Duplicate => "duplicate",
- Self::Fraudulent => "fradulent",
- Self::RequestedByCustomer => "requested_by_customer",
- Self::Abandoned => "abandoned",
- })
- }
-}
-
#[derive(Debug, Deserialize, Serialize, Copy, Clone)]
pub struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>,
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index 69bf3f72493..6292f5693af 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -653,18 +653,18 @@ impl
.clone(),
) {
(
- Some(paypal::EnrollementStatus::Ready),
+ Some(paypal::EnrollmentStatus::Ready),
Some(paypal::AuthenticationStatus::Success),
paypal::LiabilityShift::Possible,
)
| (
- Some(paypal::EnrollementStatus::Ready),
+ Some(paypal::EnrollmentStatus::Ready),
Some(paypal::AuthenticationStatus::Attempted),
paypal::LiabilityShift::Possible,
)
- | (Some(paypal::EnrollementStatus::NotReady), None, paypal::LiabilityShift::No)
- | (Some(paypal::EnrollementStatus::Unavailable), None, paypal::LiabilityShift::No)
- | (Some(paypal::EnrollementStatus::Bypassed), None, paypal::LiabilityShift::No) => {
+ | (Some(paypal::EnrollmentStatus::NotReady), None, paypal::LiabilityShift::No)
+ | (Some(paypal::EnrollmentStatus::Unavailable), None, paypal::LiabilityShift::No)
+ | (Some(paypal::EnrollmentStatus::Bypassed), None, paypal::LiabilityShift::No) => {
Ok(types::PaymentsPreProcessingRouterData {
status: storage_enums::AttemptStatus::AuthenticationSuccessful,
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -698,7 +698,7 @@ impl
.authentication_result
.three_d_secure
.enrollment_status
- .unwrap_or(paypal::EnrollementStatus::Null),
+ .unwrap_or(paypal::EnrollmentStatus::Null),
liability_response
.payment_source
.card
@@ -714,7 +714,7 @@ impl
}
}
// if card does not supports 3DS check for liability
- paypal::PaypalPreProcessingResponse::PaypalNonLiablityResponse(_) => {
+ paypal::PaypalPreProcessingResponse::PaypalNonLiabilityResponse(_) => {
Ok(types::PaymentsPreProcessingRouterData {
status: storage_enums::AttemptStatus::AuthenticationSuccessful,
response: Ok(types::PaymentsResponseData::TransactionResponse {
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index aff3be9bd22..bd023e703a6 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -946,7 +946,7 @@ pub struct PaypalThreeDsResponse {
#[serde(untagged)]
pub enum PaypalPreProcessingResponse {
PaypalLiabilityResponse(PaypalLiabilityResponse),
- PaypalNonLiablityResponse(PaypalNonLiablityResponse),
+ PaypalNonLiabilityResponse(PaypalNonLiabilityResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -955,7 +955,7 @@ pub struct PaypalLiabilityResponse {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PaypalNonLiablityResponse {
+pub struct PaypalNonLiabilityResponse {
payment_source: CardsData,
}
@@ -976,7 +976,7 @@ pub struct PaypalThreeDsParams {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreeDsCheck {
- pub enrollment_status: Option<EnrollementStatus>,
+ pub enrollment_status: Option<EnrollmentStatus>,
pub authentication_status: Option<AuthenticationStatus>,
}
@@ -989,7 +989,7 @@ pub enum LiabilityShift {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum EnrollementStatus {
+pub enum EnrollmentStatus {
Null,
#[serde(rename = "Y")]
Ready,
diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs
index 9e514a43553..b9daf49fac0 100644
--- a/crates/router/src/connector/powertranz.rs
+++ b/crates/router/src/connector/powertranz.rs
@@ -115,7 +115,7 @@ impl ConnectorCommon for Powertranz {
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- // For error scenerios connector respond with 200 http status code and error response object in response
+ // For error scenarios connector respond with 200 http status code and error response object in response
// For http status code other than 200 they send empty response back
event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&serde_json::json!({"error_response": std::str::from_utf8(&res.response).unwrap_or("")})));
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 5d46148b01d..31910f4b932 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -357,7 +357,7 @@ pub struct RefundResponse {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
- //Some field related to forign exchange and split payment can be added as and when implemented
+ //Some field related to foreign exchange and split payment can be added as and when implemented
pub id: String,
pub payment: String,
pub amount: i64,
diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs
index b28fb5b27ef..c7cb321f719 100644
--- a/crates/router/src/connector/riskified.rs
+++ b/crates/router/src/connector/riskified.rs
@@ -392,7 +392,7 @@ impl
req: &frm_types::FrmFulfillmentRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let req_obj = riskified::RiskifiedFullfillmentRequest::try_from(req)?;
+ let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/router/src/connector/riskified/transformers/api.rs
index f425ecdfe56..51802c8f96a 100644
--- a/crates/router/src/connector/riskified/transformers/api.rs
+++ b/crates/router/src/connector/riskified/transformers/api.rs
@@ -451,8 +451,8 @@ impl TryFrom<&frm_types::FrmTransactionRouterData> for TransactionSuccessRequest
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
-pub struct RiskifiedFullfillmentRequest {
- order: OrderFullfillment,
+pub struct RiskifiedFulfillmentRequest {
+ order: OrderFulfillment,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
@@ -465,7 +465,7 @@ pub enum FulfillmentRequestStatus {
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
-pub struct OrderFullfillment {
+pub struct OrderFulfillment {
id: String,
fulfillments: FulfilmentData,
}
@@ -481,11 +481,11 @@ pub struct FulfilmentData {
tracking_url: Option<String>,
}
-impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFullfillmentRequest {
+impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest {
type Error = Error;
fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
Ok(Self {
- order: OrderFullfillment {
+ order: OrderFulfillment {
id: item.attempt_id.clone(),
fulfillments: FulfilmentData {
fulfillment_id: item.payment_id.clone(),
diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs
index 6e63d5487e5..c28fbc0550b 100644
--- a/crates/router/src/connector/signifyd.rs
+++ b/crates/router/src/connector/signifyd.rs
@@ -498,7 +498,7 @@ impl
req: &frm_types::FrmFulfillmentRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let req_obj = signifyd::FrmFullfillmentSignifydRequest::try_from(req)?;
+ let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj.clone())))
}
@@ -530,9 +530,9 @@ impl
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> {
- let response: signifyd::FrmFullfillmentSignifydApiResponse = res
+ let response: signifyd::FrmFulfillmentSignifydApiResponse = res
.response
- .parse_struct("FrmFullfillmentSignifydApiResponse Sale")
+ .parse_struct("FrmFulfillmentSignifydApiResponse Sale")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs
index b738ec00fcf..da1670ea1b8 100644
--- a/crates/router/src/connector/signifyd/transformers/api.rs
+++ b/crates/router/src/connector/signifyd/transformers/api.rs
@@ -353,7 +353,7 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequ
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
-pub struct FrmFullfillmentSignifydRequest {
+pub struct FrmFulfillmentSignifydRequest {
pub order_id: String,
pub fulfillment_status: Option<FulfillmentStatus>,
pub fulfillments: Vec<Fulfillments>,
@@ -388,7 +388,7 @@ pub struct Product {
pub item_id: String,
}
-impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFullfillmentSignifydRequest {
+impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
Ok(Self {
@@ -470,7 +470,7 @@ impl From<core_types::Address> for Address {
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
-pub struct FrmFullfillmentSignifydApiResponse {
+pub struct FrmFulfillmentSignifydApiResponse {
pub order_id: String,
pub shipment_ids: Vec<String>,
}
@@ -479,7 +479,7 @@ impl
TryFrom<
ResponseRouterData<
Fulfillment,
- FrmFullfillmentSignifydApiResponse,
+ FrmFulfillmentSignifydApiResponse,
frm_types::FraudCheckFulfillmentData,
frm_types::FraudCheckResponseData,
>,
@@ -494,7 +494,7 @@ impl
fn try_from(
item: ResponseRouterData<
Fulfillment,
- FrmFullfillmentSignifydApiResponse,
+ FrmFulfillmentSignifydApiResponse,
frm_types::FraudCheckFulfillmentData,
frm_types::FraudCheckResponseData,
>,
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 4673cce4d81..7da7e85b872 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -154,8 +154,8 @@ pub struct StripeMetadata {
// merchant_reference_id
#[serde(rename(serialize = "metadata[order_id]"))]
pub order_id: Option<String>,
- // to check whether the order_id is refund_id or payemnt_id
- // before deployment, order id is set to payemnt_id in refunds but now it is set as refund_id
+ // to check whether the order_id is refund_id or payment_id
+ // before deployment, order id is set to payment_id in refunds but now it is set as refund_id
// it is set as string instead of bool because stripe pass it as string even if we set it as bool
#[serde(rename(serialize = "metadata[is_refund_id_as_reference]"))]
pub is_refund_id_as_reference: Option<String>,
@@ -2845,7 +2845,7 @@ pub struct StripeVerifyWithMicroDepositsResponse {
pub struct StripeBankTransferDetails {
pub amount_remaining: i64,
pub currency: String,
- pub financial_addresses: Vec<StripeFinanicalInformation>,
+ pub financial_addresses: Vec<StripeFinancialInformation>,
pub hosted_instructions_url: Option<String>,
pub reference: Option<String>,
#[serde(rename = "type")]
@@ -2867,7 +2867,7 @@ pub struct QrCodeResponse {
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
-pub struct StripeFinanicalInformation {
+pub struct StripeFinancialInformation {
pub iban: Option<SepaFinancialDetails>,
pub sort_code: Option<BacsFinancialDetails>,
pub supported_networks: Vec<String>,
diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs
index e4a49d7c566..3a241fe4ed6 100644
--- a/crates/router/src/connector/wise.rs
+++ b/crates/router/src/connector/wise.rs
@@ -628,7 +628,7 @@ impl
_req: &types::PayoutsRouterData<api::PoEligibility>,
_connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- // Eligiblity check for cards is not implemented
+ // Eligibility check for cards is not implemented
Err(
errors::ConnectorError::NotImplemented("Payout Eligibility for Wise".to_string())
.into(),
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 732596d5c1c..4ad62c5a078 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -42,7 +42,7 @@ pub async fn create_customer(
// We first need to validate whether the customer with the given customer id already exists
// this may seem like a redundant db call, as the insert_customer will anyway return this error
//
- // Consider a scenerio where the address is inserted and then when inserting the customer,
+ // Consider a scenario where the address is inserted and then when inserting the customer,
// it errors out, now the address that was inserted is not deleted
match db
.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, &key_store)
diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs
index c5a05a169c7..0e36ed165b2 100644
--- a/crates/router/src/core/metrics.rs
+++ b/crates/router/src/core/metrics.rs
@@ -22,7 +22,7 @@ counter_metric!(
counter_metric!(
ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC,
GLOBAL_METER
-); //No. of status validation failures while accpeting a dispute
+); //No. of status validation failures while accepting a dispute
counter_metric!(
EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC,
GLOBAL_METER
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index 722aad26c0d..ff7c56d526c 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -46,7 +46,7 @@ pub async fn retrieve_payment_link(
Ok(services::ApplicationResponse::Json(response))
}
-pub async fn intiate_payment_link_flow(
+pub async fn initiate_payment_link_flow(
state: AppState,
merchant_account: domain::MerchantAccount,
merchant_id: String,
diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs
index 4d79b923163..dd6898724c5 100644
--- a/crates/router/src/routes/payment_link.rs
+++ b/crates/router/src/routes/payment_link.rs
@@ -68,7 +68,7 @@ pub async fn initiate_payment_link(
&req,
payload.clone(),
|state, auth, _| {
- intiate_payment_link_flow(
+ initiate_payment_link_flow(
state,
auth.merchant_account,
payload.merchant_id.clone(),
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 8a7b1370d4c..3ae8c78234a 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -437,7 +437,7 @@ async fn should_refund_succeeded_payment_multiple_times() {
}
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs
index aa0da693504..66f8a42a47f 100644
--- a/crates/router/tests/connectors/airwallex.rs
+++ b/crates/router/tests/connectors/airwallex.rs
@@ -349,7 +349,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[serial_test::serial]
#[actix_web::test]
diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs
index e613696bd92..46f61271ee4 100644
--- a/crates/router/tests/connectors/bambora.rs
+++ b/crates/router/tests/connectors/bambora.rs
@@ -287,7 +287,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/bankofamerica.rs b/crates/router/tests/connectors/bankofamerica.rs
index 938a5eaf830..ca54e9c97b9 100644
--- a/crates/router/tests/connectors/bankofamerica.rs
+++ b/crates/router/tests/connectors/bankofamerica.rs
@@ -296,7 +296,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/billwerk.rs b/crates/router/tests/connectors/billwerk.rs
index b1062478bf9..6795aa40115 100644
--- a/crates/router/tests/connectors/billwerk.rs
+++ b/crates/router/tests/connectors/billwerk.rs
@@ -296,7 +296,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/boku.rs b/crates/router/tests/connectors/boku.rs
index 995cae5a231..2f496562e1d 100644
--- a/crates/router/tests/connectors/boku.rs
+++ b/crates/router/tests/connectors/boku.rs
@@ -295,7 +295,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index 5e2592eaa30..85b55afc8ea 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -311,7 +311,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[serial_test::serial]
diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs
index b42e7d2f51e..edb24646bcb 100644
--- a/crates/router/tests/connectors/dlocal.rs
+++ b/crates/router/tests/connectors/dlocal.rs
@@ -282,7 +282,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/dummyconnector.rs b/crates/router/tests/connectors/dummyconnector.rs
index 34a351241b1..76f72b64907 100644
--- a/crates/router/tests/connectors/dummyconnector.rs
+++ b/crates/router/tests/connectors/dummyconnector.rs
@@ -298,7 +298,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs
index f564f31df12..5e484e5d771 100644
--- a/crates/router/tests/connectors/fiserv.rs
+++ b/crates/router/tests/connectors/fiserv.rs
@@ -340,7 +340,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
#[serial_test::serial]
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index d09255182e2..c7934b3711a 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -459,7 +459,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
@@ -623,7 +623,7 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() {
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card issuer.
#[actix_web::test]
diff --git a/crates/router/tests/connectors/globepay.rs b/crates/router/tests/connectors/globepay.rs
index 7fedcf85ded..70167970210 100644
--- a/crates/router/tests/connectors/globepay.rs
+++ b/crates/router/tests/connectors/globepay.rs
@@ -297,7 +297,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/gocardless.rs b/crates/router/tests/connectors/gocardless.rs
index 3efb86446d9..0564ea7da6d 100644
--- a/crates/router/tests/connectors/gocardless.rs
+++ b/crates/router/tests/connectors/gocardless.rs
@@ -295,7 +295,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/helcim.rs b/crates/router/tests/connectors/helcim.rs
index f434f3b8a65..dc3bb4d47e6 100644
--- a/crates/router/tests/connectors/helcim.rs
+++ b/crates/router/tests/connectors/helcim.rs
@@ -295,7 +295,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/multisafepay.rs b/crates/router/tests/connectors/multisafepay.rs
index eafc8a22fff..f35fe05bf36 100644
--- a/crates/router/tests/connectors/multisafepay.rs
+++ b/crates/router/tests/connectors/multisafepay.rs
@@ -323,7 +323,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[ignore = "Connector doesn't fail invalid cvv scenario"]
#[actix_web::test]
diff --git a/crates/router/tests/connectors/noon.rs b/crates/router/tests/connectors/noon.rs
index 13453580240..7e0bb954c6c 100644
--- a/crates/router/tests/connectors/noon.rs
+++ b/crates/router/tests/connectors/noon.rs
@@ -305,7 +305,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs
index 26e141d8162..04a83b3a606 100644
--- a/crates/router/tests/connectors/nuvei.rs
+++ b/crates/router/tests/connectors/nuvei.rs
@@ -242,7 +242,7 @@ async fn should_partially_refund_succeeded_payment() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/opayo.rs b/crates/router/tests/connectors/opayo.rs
index d05bcef1102..f4badf9b116 100644
--- a/crates/router/tests/connectors/opayo.rs
+++ b/crates/router/tests/connectors/opayo.rs
@@ -300,7 +300,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/payeezy.rs b/crates/router/tests/connectors/payeezy.rs
index 320db9c776f..bfc0cb13650 100644
--- a/crates/router/tests/connectors/payeezy.rs
+++ b/crates/router/tests/connectors/payeezy.rs
@@ -365,7 +365,7 @@ async fn should_refund_succeeded_payment_multiple_times() {
#[ignore]
async fn should_sync_refund() {}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card issuer.
#[actix_web::test]
diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs
index 0e53f096ef4..cda6f22e153 100644
--- a/crates/router/tests/connectors/payme.rs
+++ b/crates/router/tests/connectors/payme.rs
@@ -363,7 +363,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs
index adef1d202ae..14690ae2a73 100644
--- a/crates/router/tests/connectors/paypal.rs
+++ b/crates/router/tests/connectors/paypal.rs
@@ -440,7 +440,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
diff --git a/crates/router/tests/connectors/placetopay.rs b/crates/router/tests/connectors/placetopay.rs
index 2290e7b2f32..41675b9751b 100644
--- a/crates/router/tests/connectors/placetopay.rs
+++ b/crates/router/tests/connectors/placetopay.rs
@@ -295,7 +295,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/powertranz.rs b/crates/router/tests/connectors/powertranz.rs
index 75d6f7fe1df..0701ec006d9 100644
--- a/crates/router/tests/connectors/powertranz.rs
+++ b/crates/router/tests/connectors/powertranz.rs
@@ -303,7 +303,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/prophetpay.rs b/crates/router/tests/connectors/prophetpay.rs
index 9443ae0850b..9a0e2dbfa0e 100644
--- a/crates/router/tests/connectors/prophetpay.rs
+++ b/crates/router/tests/connectors/prophetpay.rs
@@ -295,7 +295,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs
index 2e334954605..8f11fbfa1d8 100644
--- a/crates/router/tests/connectors/shift4.rs
+++ b/crates/router/tests/connectors/shift4.rs
@@ -144,7 +144,7 @@ async fn should_void_authorized_payment() {
assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); //shift4 doesn't allow voiding a payment
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs
index 597510d6f91..01d90c73c42 100644
--- a/crates/router/tests/connectors/square.rs
+++ b/crates/router/tests/connectors/square.rs
@@ -428,7 +428,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs
index 75ff364e312..d16f209a49a 100644
--- a/crates/router/tests/connectors/stax.rs
+++ b/crates/router/tests/connectors/stax.rs
@@ -455,7 +455,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs
index 50856b3bd57..48cd165767c 100644
--- a/crates/router/tests/connectors/trustpay.rs
+++ b/crates/router/tests/connectors/trustpay.rs
@@ -177,7 +177,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/router/tests/connectors/tsys.rs b/crates/router/tests/connectors/tsys.rs
index 1200541d025..d7a688bd128 100644
--- a/crates/router/tests/connectors/tsys.rs
+++ b/crates/router/tests/connectors/tsys.rs
@@ -339,7 +339,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/volt.rs b/crates/router/tests/connectors/volt.rs
index f46bbb9d49a..7bcdf63d918 100644
--- a/crates/router/tests/connectors/volt.rs
+++ b/crates/router/tests/connectors/volt.rs
@@ -295,7 +295,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index d56712fd77d..c9a7be2b0a6 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -301,7 +301,7 @@ async fn should_sync_refund() {
);
}
-// Cards Negative scenerios
+// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
diff --git a/crates/test_utils/tests/connectors/authorizedotnet_ui.rs b/crates/test_utils/tests/connectors/authorizedotnet_ui.rs
index b1bea20c1b0..66e241a98e7 100644
--- a/crates/test_utils/tests/connectors/authorizedotnet_ui.rs
+++ b/crates/test_utils/tests/connectors/authorizedotnet_ui.rs
@@ -14,7 +14,7 @@ impl SeleniumTest for AuthorizedotnetSeleniumTest {
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
- let amount = rand::thread_rng().gen_range(1..1000); //This connector detects it as fradulent payment if the same amount is used for multiple payments so random amount is passed for testing
+ let amount = rand::thread_rng().gen_range(1..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing
let pub_key = conn
.get_configs()
.automation_configs
diff --git a/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs b/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs
index b17fd80b0a1..e470691bd07 100644
--- a/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs
+++ b/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs
@@ -13,7 +13,7 @@ impl SeleniumTest for AuthorizedotnetSeleniumTest {
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
- let amount = rand::thread_rng().gen_range(50..1000); //This connector detects it as fradulent payment if the same amount is used for multiple payments so random amount is passed for testing(
+ let amount = rand::thread_rng().gen_range(50..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing(
conn.make_webhook_test(
web_driver,
&format!("{CHEKOUT_BASE_URL}/saved/227?amount={amount}"),
diff --git a/loadtest/k6/helper/k6-summary.js b/loadtest/k6/helper/k6-summary.js
index 83935caa8b9..f8135cb5a10 100644
--- a/loadtest/k6/helper/k6-summary.js
+++ b/loadtest/k6/helper/k6-summary.js
@@ -160,26 +160,26 @@ function toFixedNoTrailingZerosTrunc(val, prec) {
return toFixedNoTrailingZeros(Math.trunc(mult * val) / mult, prec)
}
-function humanizeGenericDuration(dur) {
- if (dur === 0) {
+function humanizeGenericDuration(duration) {
+ if (duration === 0) {
return '0s'
}
- if (dur < 0.001) {
+ if (duration < 0.001) {
// smaller than a microsecond, print nanoseconds
- return Math.trunc(dur * 1000000) + 'ns'
+ return Math.trunc(duration * 1000000) + 'ns'
}
- if (dur < 1) {
+ if (duration < 1) {
// smaller than a millisecond, print microseconds
- return toFixedNoTrailingZerosTrunc(dur * 1000, 2) + 'µs'
+ return toFixedNoTrailingZerosTrunc(duration * 1000, 2) + 'µs'
}
- if (dur < 1000) {
+ if (duration < 1000) {
// duration is smaller than a second
- return toFixedNoTrailingZerosTrunc(dur, 2) + 'ms'
+ return toFixedNoTrailingZerosTrunc(duration, 2) + 'ms'
}
- var result = toFixedNoTrailingZerosTrunc((dur % 60000) / 1000, dur > 60000 ? 0 : 2) + 's'
- var rem = Math.trunc(dur / 60000)
+ var result = toFixedNoTrailingZerosTrunc((duration % 60000) / 1000, duration > 60000 ? 0 : 2) + 's'
+ var rem = Math.trunc(duration / 60000)
if (rem < 1) {
// less than a minute
return result
@@ -193,12 +193,12 @@ function humanizeGenericDuration(dur) {
return rem + 'h' + result
}
-function humanizeDuration(dur, timeUnit) {
+function humanizeDuration(duration, timeUnit) {
if (timeUnit !== '' && unitMap.hasOwnProperty(timeUnit)) {
- return (dur * unitMap[timeUnit].coef).toFixed(2) + unitMap[timeUnit].unit
+ return (duration * unitMap[timeUnit].coef).toFixed(2) + unitMap[timeUnit].unit
}
- return humanizeGenericDuration(dur)
+ return humanizeGenericDuration(duration)
}
function humanizeValue(val, metric, timeUnit) {
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index ad360ab7dd7..63b5128984e 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -7770,7 +7770,7 @@
"default_payment_method_id": {
"type": "string",
"description": "The unique identifier of the Payment method",
- "example": "card_rGK4Vi5iSW70MY7J2mIy",
+ "example": "card_rGK4Vi5iSW70MY7J2mIg",
"nullable": true
},
"customer_id": {
@@ -12529,7 +12529,7 @@
"payment_method_id": {
"type": "string",
"description": "The unique identifier of the Payment method",
- "example": "card_rGK4Vi5iSW70MY7J2mIy"
+ "example": "card_rGK4Vi5iSW70MY7J2mIg"
},
"deleted": {
"type": "boolean",
@@ -12655,7 +12655,7 @@
"payment_method_id": {
"type": "string",
"description": "The unique identifier of the Payment method",
- "example": "card_rGK4Vi5iSW70MY7J2mIy"
+ "example": "card_rGK4Vi5iSW70MY7J2mIg"
},
"payment_method": {
"$ref": "#/components/schemas/PaymentMethod"
@@ -16355,7 +16355,7 @@
"properties": {
"payment_id": {
"type": "string",
- "description": "The payment id against which refund is to be intiated",
+ "description": "The payment id against which refund is to be initiated",
"example": "pay_mbabizu24mvu3mela5njyhpit4",
"maxLength": 30,
"minLength": 30
@@ -16432,7 +16432,7 @@
},
"payment_id": {
"type": "string",
- "description": "The payment id against which refund is intiated"
+ "description": "The payment id against which refund is initiated"
},
"amount": {
"type": "integer",
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/.meta.json
index 773ed0638cb..6e38554431e 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/.meta.json
@@ -6,7 +6,7 @@
"Scenario4-Create payment with Manual capture",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Create a mandate and recurring payment",
"Scenario11-Partial refund",
@@ -21,4 +21,4 @@
"Scenario20-Pass Invalid CVV for save card flow and verify failed payment",
"Scenario21-Don't Pass CVV for save card flow and verify failed payment Copy"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/.meta.json
index 944c90c84cc..5c8008c1882 100644
--- a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/.meta.json
@@ -6,8 +6,8 @@
"Scenario4-Create payment with Manual capture",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Partial refund"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.prerequest.js b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.prerequest.js
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/airwallex/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/.meta.json
index 0a95a9d8fc5..317d5a30c98 100644
--- a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/.meta.json
@@ -1,6 +1,6 @@
{
"childrenOrder": [
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false"
+ "Scenario7-Create 3DS payment with confirm false"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/bambora_3ds/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/.meta.json
index 944c90c84cc..5c8008c1882 100644
--- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/.meta.json
@@ -6,8 +6,8 @@
"Scenario4-Create payment with Manual capture",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Partial refund"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/.meta.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/.meta.json
index 82f7a33dc5c..d8253c73fe0 100644
--- a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/.meta.json
+++ b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/.meta.json
@@ -6,7 +6,7 @@
"Scenario4-Create payment with Manual capture",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Partial refund",
"Scenario11-Create a mandate and recurring payment",
@@ -21,4 +21,4 @@
"Scenario19-Bank Transfer-ach",
"Scenario19-Bank Transfer-ach Copy 2"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/.meta.json
index 53747092aa6..48b665ffbac 100644
--- a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/.meta.json
@@ -4,11 +4,11 @@
"Scenario2-Create payment with confirm false",
"Scenario3-Create payment without PMD",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario15-Bank Redirect-Ideal",
"Scenario15- Wallets Paypal",
"Scenario16-Bank Redirect-sofort",
"Scenario17-Bank Redirect-eps",
"Scenario18-Bank Redirect-giropay"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/mollie/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/.meta.json
index 9d030385b7f..a9c93cb346e 100644
--- a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/.meta.json
@@ -2,6 +2,6 @@
"childrenOrder": [
"Scenario1-Create payment without PMD",
"Scenario2-Create 3DS payment",
- "Scenario3-Create 3DS payment with confrm false"
+ "Scenario3-Create 3DS payment with confirm false"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/multisafepay/Flow Testcases/Happy Cases/Scenario3-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/.meta.json
index 6be6a600776..93c072ae52d 100644
--- a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/.meta.json
@@ -6,11 +6,11 @@
"Scenario4-Create payment with Manual capture",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Partial refund",
"Scenario15-Bank Redirect-Ideal",
"Scenario16-Bank Redirect-sofort",
"Scenario18-Wallet paypal"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/nexinets/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/.meta.json
index 30c6364c0e4..ef2524b40ff 100644
--- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/.meta.json
@@ -8,6 +8,6 @@
"Scenario11-Create Partial Capture payment",
"Scenario5-Void the payment",
"Scenario6-Create Wallet - Paypal",
- "Scenario7-Create Wallet - Paypal with confrm false"
+ "Scenario7-Create Wallet - Paypal with confirm false"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/.meta.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/.meta.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/.meta.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/response.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/event.test.js b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/response.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/response.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/.meta.json
index 43cff6e349e..94f863e0a83 100644
--- a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/.meta.json
@@ -6,8 +6,8 @@
"Scenario3-Create payment without PMD",
"Scenario4-Create payment with Manual capture",
"Scenario5-Void the payment",
- "Scenario6-Create 3DS payment with confrm false",
+ "Scenario6-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Partial refund"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario6-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/.meta.json
index 99baecd05c7..c713a8fb042 100644
--- a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/.meta.json
@@ -5,6 +5,6 @@
"Scenario3-Create payment without PMD",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false"
+ "Scenario7-Create 3DS payment with confirm false"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/rapyd/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/.meta.json
index a5e77b7275f..166ded6ddce 100644
--- a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/.meta.json
@@ -5,7 +5,7 @@
"Scenario3-Create payment without PMD",
"Scenario4-Create payment with Manual capture",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario9-Refund full payment",
"Scenario10-Partial refund",
"Scenario15-Bank Redirect-Ideal",
@@ -13,4 +13,4 @@
"Scenario17-Bank Redirect-eps",
"Scenario18-Bank Redirect-giropay"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/shift4/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json
index 3a414a0e13c..edb8e67436a 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json
@@ -9,7 +9,7 @@
"Scenario4a-Create payment with manual_multiple capture",
"Scenario5-Void the payment",
"Scenario6-Create 3DS payment",
- "Scenario7-Create 3DS payment with confrm false",
+ "Scenario7-Create 3DS payment with confirm false",
"Scenario8-Create a failure card payment with confirm true",
"Scenario9-Refund full payment",
"Scenario9a-Partial refund",
@@ -37,4 +37,4 @@
"Scenario31-Pass payment method billing in Confirm",
"Scenario32-Ensure API Contract for Payment Method Data"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.prerequest.js
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.prerequest.js
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario7-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/.meta.json
index 949d82095ec..9ef23e53ba6 100644
--- a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/.meta.json
@@ -6,9 +6,9 @@
"Scenario3-Create payment with confirm false card holder name empty",
"Scenario4-Create payment without PMD",
"Scenario5-Create 3DS payment",
- "Scenario6-Create 3DS payment with confrm false",
+ "Scenario6-Create 3DS payment with confirm false",
"Scenario7-Refund full payment",
"Scenario8-Bank Redirect-Ideal",
"Scenario9-Bank Redirect-giropay"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.prerequest.js b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.prerequest.js
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.prerequest.js
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/.meta.json
index 4ecb9c1124f..bce12673620 100644
--- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/.meta.json
@@ -4,6 +4,6 @@
"Scenario2-Create payment with confirm false",
"Scenario3-Create payment without PMD",
"Scenario4-Create 3DS payment",
- "Scenario5-Create 3DS payment with confrm false"
+ "Scenario5-Create 3DS payment with confirm false"
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/.meta.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/.meta.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/.meta.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/.meta.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/.event.meta.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.test.js b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/event.test.js
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/event.test.js
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/request.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/request.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/response.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Confirm/response.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Confirm/response.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/.event.meta.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/.event.meta.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/event.test.js b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/event.test.js
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/event.test.js
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/request.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/response.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/response.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Create/response.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/event.test.js
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/request.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/response.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Retrieve/response.json
rename to postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confirm false/Payments - Retrieve/response.json
diff --git a/postman/collection-json/adyen_uk.postman_collection.json b/postman/collection-json/adyen_uk.postman_collection.json
index a5447103184..372e9c42c17 100644
--- a/postman/collection-json/adyen_uk.postman_collection.json
+++ b/postman/collection-json/adyen_uk.postman_collection.json
@@ -3472,7 +3472,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/airwallex.postman_collection.json b/postman/collection-json/airwallex.postman_collection.json
index f2e804f2b3e..3e30cc02a57 100644
--- a/postman/collection-json/airwallex.postman_collection.json
+++ b/postman/collection-json/airwallex.postman_collection.json
@@ -2844,7 +2844,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -7319,4 +7319,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/bambora_3ds.postman_collection.json b/postman/collection-json/bambora_3ds.postman_collection.json
index 0d908b26bf8..d4857bead1f 100644
--- a/postman/collection-json/bambora_3ds.postman_collection.json
+++ b/postman/collection-json/bambora_3ds.postman_collection.json
@@ -698,7 +698,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -1613,4 +1613,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/bluesnap.postman_collection.json b/postman/collection-json/bluesnap.postman_collection.json
index 137ccbe1a23..eb6e2079621 100644
--- a/postman/collection-json/bluesnap.postman_collection.json
+++ b/postman/collection-json/bluesnap.postman_collection.json
@@ -8346,7 +8346,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -11602,4 +11602,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/hyperswitch.postman_collection.json b/postman/collection-json/hyperswitch.postman_collection.json
index 4da2a81acbb..0390b917db5 100644
--- a/postman/collection-json/hyperswitch.postman_collection.json
+++ b/postman/collection-json/hyperswitch.postman_collection.json
@@ -7209,7 +7209,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/mollie.postman_collection.json b/postman/collection-json/mollie.postman_collection.json
index e2649a261fa..687fd75542c 100644
--- a/postman/collection-json/mollie.postman_collection.json
+++ b/postman/collection-json/mollie.postman_collection.json
@@ -1330,7 +1330,7 @@
]
},
{
- "name": "Scenario5-Create 3DS payment with confrm false",
+ "name": "Scenario5-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/multisafepay.postman_collection.json b/postman/collection-json/multisafepay.postman_collection.json
index 56fc6723452..245c68bf17a 100644
--- a/postman/collection-json/multisafepay.postman_collection.json
+++ b/postman/collection-json/multisafepay.postman_collection.json
@@ -1463,7 +1463,7 @@
]
},
{
- "name": "Scenario3-Create 3DS payment with confrm false",
+ "name": "Scenario3-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -3762,4 +3762,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/nexinets.postman_collection.json b/postman/collection-json/nexinets.postman_collection.json
index aa0c435f498..deb5494d6de 100644
--- a/postman/collection-json/nexinets.postman_collection.json
+++ b/postman/collection-json/nexinets.postman_collection.json
@@ -2832,7 +2832,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -8526,4 +8526,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json
index 9063afe7b0d..4587343ce0a 100644
--- a/postman/collection-json/paypal.postman_collection.json
+++ b/postman/collection-json/paypal.postman_collection.json
@@ -4887,7 +4887,7 @@
]
},
{
- "name": "Scenario7-Create Wallet - Paypal with confrm false",
+ "name": "Scenario7-Create Wallet - Paypal with confirm false",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/powertranz.postman_collection.json b/postman/collection-json/powertranz.postman_collection.json
index b158827bbb7..ecd68d45de0 100644
--- a/postman/collection-json/powertranz.postman_collection.json
+++ b/postman/collection-json/powertranz.postman_collection.json
@@ -3061,7 +3061,7 @@
]
},
{
- "name": "Scenario6-Create 3DS payment with confrm false",
+ "name": "Scenario6-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/rapyd.postman_collection.json b/postman/collection-json/rapyd.postman_collection.json
index 39ea3aab24c..db62ccaef15 100644
--- a/postman/collection-json/rapyd.postman_collection.json
+++ b/postman/collection-json/rapyd.postman_collection.json
@@ -2285,7 +2285,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -4315,4 +4315,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/shift4.postman_collection.json b/postman/collection-json/shift4.postman_collection.json
index 67a2305a4b2..ba7a905a514 100644
--- a/postman/collection-json/shift4.postman_collection.json
+++ b/postman/collection-json/shift4.postman_collection.json
@@ -2458,7 +2458,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -8976,4 +8976,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json
index c7437e8b1f1..078b0a7b281 100644
--- a/postman/collection-json/stripe.postman_collection.json
+++ b/postman/collection-json/stripe.postman_collection.json
@@ -9927,7 +9927,7 @@
]
},
{
- "name": "Scenario7-Create 3DS payment with confrm false",
+ "name": "Scenario7-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/trustpay.postman_collection.json b/postman/collection-json/trustpay.postman_collection.json
index 1203cd1793e..1b0536e1022 100644
--- a/postman/collection-json/trustpay.postman_collection.json
+++ b/postman/collection-json/trustpay.postman_collection.json
@@ -2230,7 +2230,7 @@
]
},
{
- "name": "Scenario5-Create 3DS payment with confrm false",
+ "name": "Scenario5-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
@@ -6410,4 +6410,4 @@
"type": "string"
}
]
-}
+}
\ No newline at end of file
diff --git a/postman/collection-json/zen.postman_collection.json b/postman/collection-json/zen.postman_collection.json
index 7ada350cccf..9830265508b 100644
--- a/postman/collection-json/zen.postman_collection.json
+++ b/postman/collection-json/zen.postman_collection.json
@@ -1938,7 +1938,7 @@
]
},
{
- "name": "Scenario5-Create 3DS payment with confrm false",
+ "name": "Scenario5-Create 3DS payment with confirm false",
"item": [
{
"name": "Payments - Create",
|
2024-04-02T14:31:10Z
|
## 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 -->
We use typos-cli crate to catch typos in the repo. A new version of the same was released and has caught few new typos in the repo. This PR fixes all the typos that was caught.
Reviewers can refer below commits to review easily:
Postman - a19fa982546a9919ed151a63756bb81b22fd8b91
Openapi - 303b495c5249f63aed5027816eb5edbd16674531
Loadtest - c523541aa6d995e7fb1d9328c3ed15c15b47e8c2
Connector - e006f40c881c3b6a427a0510c5d5962ab140f33d
Router, ApiModels - 7b673b1377fd13f4386b820ade6e2577524d7776
Euclid - 32c46fd6db26dcf88b74b5e6c6f788abdb48291f
Typos toml - 5d919aaae33e1ddd187e0f05c0172fcb06ea5a12
### 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)?
-->
Local sanity testing
## Checklist
<!-- Put an `x` in 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
|
1023f46c885dc2b70ccbb3931e667740695f448e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4192
|
Bug: Add NTID support for Cybersource
Add `NTID` (network transaction id) flow cybersource.
|
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 6a51e1e8cd4..346d2127649 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -297,6 +297,7 @@ pub struct CybersourceAuthorizationOptions {
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
+ previous_transaction_id: Option<Secret<String>>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
}
@@ -314,6 +315,7 @@ pub struct CybersourcePaymentInitiator {
#[serde(rename_all = "camelCase")]
pub enum CybersourcePaymentInitiatorTypes {
Customer,
+ Merchant,
}
#[derive(Debug, Serialize)]
@@ -503,6 +505,24 @@ impl
Option<String>,
),
) -> Result<Self, Self::Error> {
+ let mut commerce_indicator = solution
+ .as_ref()
+ .map(|pm_solution| match pm_solution {
+ PaymentSolution::ApplePay => network
+ .as_ref()
+ .map(|card_network| match card_network.to_lowercase().as_str() {
+ "amex" => "aesk",
+ "discover" => "dipb",
+ "mastercard" => "spa",
+ "visa" => "internet",
+ _ => "internet",
+ })
+ .unwrap_or("internet"),
+ PaymentSolution::GooglePay => "internet",
+ })
+ .unwrap_or("internet")
+ .to_string();
+
let (action_list, action_token_types, authorization_options) = if item
.router_data
.request
@@ -531,44 +551,113 @@ impl
merchant_intitiated_transaction: None,
}),
)
- } else if item.router_data.request.connector_mandate_id().is_some() {
- let original_amount = item
- .router_data
- .get_recurring_mandate_payment_data()?
- .get_original_payment_amount()?;
- let original_currency = item
+ } else if item.router_data.request.mandate_id.is_some() {
+ match item
.router_data
- .get_recurring_mandate_payment_data()?
- .get_original_payment_currency()?;
- (
- None,
- None,
- Some(CybersourceAuthorizationOptions {
- initiator: None,
- merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
- reason: None,
- original_authorized_amount: Some(utils::get_amount_as_string(
- &types::api::CurrencyUnit::Base,
- original_amount,
- original_currency,
- )?),
- }),
- }),
- )
+ .request
+ .mandate_id
+ .clone()
+ .and_then(|mandate_id| mandate_id.mandate_reference_id)
+ {
+ Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) => {
+ let original_amount = item
+ .router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_amount()?;
+ let original_currency = item
+ .router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_currency()?;
+ (
+ None,
+ None,
+ Some(CybersourceAuthorizationOptions {
+ initiator: None,
+ merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
+ reason: None,
+ original_authorized_amount: Some(utils::get_amount_as_string(
+ &types::api::CurrencyUnit::Base,
+ original_amount,
+ original_currency,
+ )?),
+ previous_transaction_id: None,
+ }),
+ }),
+ )
+ }
+ Some(api_models::payments::MandateReferenceId::NetworkMandateId(
+ network_transaction_id,
+ )) => {
+ let (original_amount, original_currency) = match network
+ .clone()
+ .map(|network| network.to_lowercase())
+ .as_deref()
+ {
+ Some("discover") => {
+ let original_amount = Some(
+ item.router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_amount()?,
+ );
+ let original_currency = Some(
+ item.router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_currency()?,
+ );
+ (original_amount, original_currency)
+ }
+ _ => {
+ let original_amount = item
+ .router_data
+ .recurring_mandate_payment_data
+ .as_ref()
+ .and_then(|recurring_mandate_payment_data| {
+ recurring_mandate_payment_data
+ .original_payment_authorized_amount
+ });
+
+ let original_currency = item
+ .router_data
+ .recurring_mandate_payment_data
+ .as_ref()
+ .and_then(|recurring_mandate_payment_data| {
+ recurring_mandate_payment_data
+ .original_payment_authorized_currency
+ });
+
+ (original_amount, original_currency)
+ }
+ };
+
+ let original_authorized_amount = match (original_amount, original_currency) {
+ (Some(original_amount), Some(original_currency)) => Some(
+ utils::to_currency_base_unit(original_amount, original_currency)?,
+ ),
+ _ => None,
+ };
+ commerce_indicator = "recurring".to_string();
+ (
+ None,
+ None,
+ Some(CybersourceAuthorizationOptions {
+ initiator: Some(CybersourcePaymentInitiator {
+ initiator_type: Some(CybersourcePaymentInitiatorTypes::Merchant),
+ credential_stored_on_file: None,
+ stored_credential_used: Some(true),
+ }),
+ merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
+ reason: Some("7".to_string()),
+ original_authorized_amount,
+ previous_transaction_id: Some(Secret::new(network_transaction_id)),
+ }),
+ }),
+ )
+ }
+ None => (None, None, None),
+ }
} else {
(None, None, None)
};
- let commerce_indicator = match network {
- Some(card_network) => match card_network.to_lowercase().as_str() {
- "amex" => "aesk",
- "discover" => "dipb",
- "mastercard" => "spa",
- "visa" => "internet",
- _ => "internet",
- },
- None => "internet",
- }
- .to_string();
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
@@ -754,11 +843,11 @@ impl
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
- card_type,
+ card_type: card_type.clone(),
},
});
- let processing_information = ProcessingInformation::try_from((item, None, None))?;
+ let processing_information = ProcessingInformation::try_from((item, None, card_type))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -1287,6 +1376,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout
}),
merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
reason: Some("5".to_owned()),
+ previous_transaction_id: None,
original_authorized_amount: None,
}),
}),
@@ -1537,6 +1627,7 @@ pub struct ClientReferenceInformation {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
+ network_transaction_id: Option<String>,
avs: Option<Avs>,
}
@@ -1667,7 +1758,7 @@ fn get_payment_response(
.processor_information
.as_ref()
.map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})),
- network_txn_id: None,
+ network_txn_id: info_response.processor_information.as_ref().and_then(|processor_information| processor_information.network_transaction_id.clone()),
connector_response_reference_id: Some(
info_response
.client_reference_information
@@ -2281,6 +2372,7 @@ impl<F>
}
}
+// zero dollar response
impl<F, T>
TryFrom<
types::ResponseRouterData<
@@ -2328,7 +2420,11 @@ impl<F, T>
redirection_data: None,
mandate_reference,
connector_metadata: None,
- network_txn_id: None,
+ network_txn_id: info_response.processor_information.as_ref().and_then(
+ |processor_information| {
+ processor_information.network_transaction_id.clone()
+ },
+ ),
connector_response_reference_id: Some(
info_response
.client_reference_information
|
2024-03-26T07:11:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add `NTID` (network transaction id) flow cybersource.
### 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)?
-->
enabled `pg_agnotic` flag
```
curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT_Token' \
--data '{
"enabled": true
}'
```
Created a mandate or CIT in cybersource
<img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92">
```
{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "singh",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
DB screenshot where `network_transaction_id` is stored in the `payment_methods` table

Create a payment with confirm false
<img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468">
List payment methods for customer
```
curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: api-key'
```
<img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293">
Confirm the payment by passing the connector as stripe in routing
```
{
"amount": 300,
"currency": "USD",
"confirm": false,
"customer_id": "cyb111",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"off_session": true,
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
}
}
```
```
curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \
--header 'api-key: api-key' \
--header 'Content-Type: application/json' \
--data '{
"payment_token": "payment_token",
"client_secret": "client_secret",
"payment_method": "card"
}'
```
<img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
b58d7a8e62eef9880f717731063101bf92af3f34
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4178
|
Bug: [FIX] fix 404 when not sending payment_id to compatibility layer
|
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index 87560032ea4..56bcb2d58d0 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -7,7 +7,8 @@ use router_env::{instrument, tracing, Flow, Tag};
use crate::{
compatibility::{stripe::errors, wrap},
core::{api_locking::GetLockingInput, payment_methods::Oss, payments},
- logger, routes,
+ logger,
+ routes::{self, payments::get_or_generate_payment_id},
services::{api, authentication as auth},
types::api as api_types,
};
@@ -26,15 +27,19 @@ pub async fn payment_intents_create(
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
+
tracing::Span::current().record("payment_id", &payload.id.clone().unwrap_or_default());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload);
- let create_payment_req: payment_types::PaymentsRequest = match payload.try_into() {
+ let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
+ if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) {
+ return api::log_and_return_error_response(err);
+ }
let flow = Flow::PaymentsCreate;
let locking_action = create_payment_req.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
|
2024-03-19T09:18:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
## Description
<!-- Describe your changes in detail -->
Fixed the bug where `compatibility` layer would throw 404 if `payment_id` is not sent.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue 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 fixes the bug where `compatibility` layer would throw 404 if `payment_id` is not sent in request
## How did you test 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 without passing the `payment_id` to stripe compatibility layer
```bash
curl --location 'http://localhost:8080/vs/v1/payment_intents' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'User-Agent: helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \
--header 'api-key: dev_N1nUguE0Mue3z1CrAMAt5ZahpeFGVcwzuiBM9mM6DR9ClR4r5uFrKfI7UcdDnToM' \
--data-urlencode 'amount=2000' \
--data-urlencode 'currency=AED' \
--data-urlencode 'confirm=true' \
--data-urlencode 'payment_method_data%5Btype%5D=card' \
--data-urlencode 'payment_method_data%5Bcard%5D%5Bnumber%5D=4242424242424242' \
--data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_month%5D=12' \
--data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_year%5D=2030' \
--data-urlencode 'payment_method_data%5Bcard%5D%5Bcvc%5D=123' \
--data-urlencode 'connector%5B%5D=stripe' \
--data-urlencode 'capture_method=automatic' \
--data-urlencode 'customer=sahkal' \
--data-urlencode 'description=Card Payment' \
--data-urlencode 'off_session=true' \
--data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Buser_agent%5D=helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \
--data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Bip_address%5D=123.32.25.123' \
--data-urlencode 'mandate_data%5Bamount%5D=20877' \
--data-urlencode 'setup_future_usage=off_session' \
--data-urlencode 'return_url=https://juspay.in' \
--data-urlencode 'metadata%5Btxn_Id%5D=sahkal_payment' \
--data-urlencode 'metadata%5BtxnUuid%5D=94hfdmoakosdkifdhaisl' \
--data-urlencode 'metadata%5Bmerchant_id%5D=sahkal' \
--data-urlencode 'metadata%5Beuler_merchant_id%5D=global_installment' \
--data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' \
--data-urlencode 'payment_method_data%5Bcard%5D%5Bholder_name%5D=sahkal'
```
- It should return 200 with auto generated `payment_id`
## Checklist
<!-- Put an `x` in 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
|
a843713126cea102064b342b6fc82429d89d758a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4195
|
Bug: Update aws dependencies to latest version
Update rust aws dependencies to their latest version
|
diff --git a/Cargo.lock b/Cargo.lock
index 13d6ca93df9..3c344844738 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -9,7 +9,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f7b0a21988c1bf877cf4759ef5ddaac04c1c9fe808c9142ecb78ba97d97a28a"
dependencies = [
"bitflags 2.6.0",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-core",
"futures-sink",
"memchr",
@@ -49,7 +49,7 @@ dependencies = [
"base64 0.22.1",
"bitflags 2.6.0",
"brotli",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"bytestring",
"derive_more",
"encoding_rs",
@@ -81,7 +81,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb"
dependencies = [
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -93,7 +93,7 @@ dependencies = [
"actix-multipart-derive",
"actix-utils",
"actix-web",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"derive_more",
"futures-core",
"futures-util",
@@ -120,7 +120,7 @@ dependencies = [
"parse-size",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -227,7 +227,7 @@ dependencies = [
"actix-utils",
"actix-web-codegen",
"ahash 0.8.11",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"bytestring",
"cfg-if 1.0.0",
"cookie 0.16.2",
@@ -262,7 +262,7 @@ dependencies = [
"actix-router",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -347,9 +347,9 @@ dependencies = [
"actix-web",
"api_models",
"async-trait",
- "aws-config 1.5.5",
+ "aws-config",
"aws-sdk-lambda",
- "aws-smithy-types 1.2.4",
+ "aws-smithy-types",
"bigdecimal",
"common_enums",
"common_utils",
@@ -370,7 +370,7 @@ dependencies = [
"sqlx",
"storage_impl",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"tokio 1.40.0",
]
@@ -520,7 +520,7 @@ dependencies = [
"nom",
"num-traits",
"rusticata-macros",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -532,7 +532,7 @@ checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"synstructure 0.13.1",
]
@@ -544,7 +544,7 @@ checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -565,7 +565,7 @@ dependencies = [
"async-trait",
"bb8",
"diesel",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"tracing",
]
@@ -613,7 +613,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -624,7 +624,7 @@ checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -661,7 +661,7 @@ dependencies = [
"actix-tls",
"actix-utils",
"base64 0.22.1",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"cfg-if 1.0.0",
"cookie 0.16.2",
"derive_more",
@@ -684,54 +684,24 @@ dependencies = [
[[package]]
name = "aws-config"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bcdcf0d683fe9c23d32cf5b53c9918ea0a500375a9fb20109802552658e576c9"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-http",
- "aws-sdk-sso 0.28.0",
- "aws-sdk-sts 0.28.0",
- "aws-smithy-async 0.55.3",
- "aws-smithy-client",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-json 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
- "fastrand 1.9.0",
- "hex",
- "http 0.2.12",
- "hyper 0.14.30",
- "ring 0.16.20",
- "time",
- "tokio 1.40.0",
- "tower",
- "tracing",
- "zeroize",
-]
-
-[[package]]
-name = "aws-config"
-version = "1.5.5"
+version = "1.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e95816a168520d72c0e7680c405a5a8c1fb6a035b4bc4b9d7b0de8e1a941697"
+checksum = "9b49afaa341e8dd8577e1a2200468f98956d6eda50bcf4a53246cc00174ba924"
dependencies = [
- "aws-credential-types 1.2.1",
+ "aws-credential-types",
"aws-runtime",
- "aws-sdk-sso 1.40.0",
+ "aws-sdk-sso",
"aws-sdk-ssooidc",
- "aws-sdk-sts 1.40.0",
- "aws-smithy-async 1.2.1",
- "aws-smithy-http 0.60.10",
+ "aws-sdk-sts",
+ "aws-smithy-async",
+ "aws-smithy-http 0.60.12",
"aws-smithy-json 0.60.7",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "aws-types 1.3.3",
- "bytes 1.7.1",
- "fastrand 2.1.1",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
+ "fastrand",
"hex",
"http 0.2.12",
"ring 0.17.8",
@@ -744,80 +714,33 @@ dependencies = [
[[package]]
name = "aws-credential-types"
-version = "0.55.3"
+version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fcdb2f7acbc076ff5ad05e7864bdb191ca70a6fd07668dc3a1a8bcd051de5ae"
+checksum = "4471bef4c22a06d2c7a1b6492493d3fdf24a805323109d6874f9c94d5906ac14"
dependencies = [
- "aws-smithy-async 0.55.3",
- "aws-smithy-types 0.55.3",
- "fastrand 1.9.0",
- "tokio 1.40.0",
- "tracing",
- "zeroize",
-]
-
-[[package]]
-name = "aws-credential-types"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60e8f6b615cb5fc60a98132268508ad104310f0cfb25a1c22eee76efdf9154da"
-dependencies = [
- "aws-smithy-async 1.2.1",
+ "aws-smithy-async",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
+ "aws-smithy-types",
"zeroize",
]
-[[package]]
-name = "aws-endpoint"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8cce1c41a6cfaa726adee9ebb9a56fcd2bbfd8be49fd8a04c5e20fd968330b04"
-dependencies = [
- "aws-smithy-http 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-types 0.55.3",
- "http 0.2.12",
- "regex",
- "tracing",
-]
-
-[[package]]
-name = "aws-http"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aadbc44e7a8f3e71c8b374e03ecd972869eb91dd2bc89ed018954a52ba84bc44"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-smithy-http 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
- "http 0.2.12",
- "http-body 0.4.6",
- "lazy_static",
- "percent-encoding",
- "pin-project-lite",
- "tracing",
-]
-
[[package]]
name = "aws-runtime"
-version = "1.4.2"
+version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2424565416eef55906f9f8cece2072b6b6a76075e3ff81483ebe938a89a4c05f"
+checksum = "0aff45ffe35196e593ea3b9dd65b320e51e2dda95aff4390bc459e461d09c6ad"
dependencies = [
- "aws-credential-types 1.2.1",
- "aws-sigv4 1.2.3",
- "aws-smithy-async 1.2.1",
- "aws-smithy-eventstream 0.60.4",
- "aws-smithy-http 0.60.10",
+ "aws-credential-types",
+ "aws-sigv4",
+ "aws-smithy-async",
+ "aws-smithy-eventstream",
+ "aws-smithy-http 0.62.0",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "aws-types 1.3.3",
- "bytes 1.7.1",
- "fastrand 2.1.1",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
+ "fastrand",
"http 0.2.12",
"http-body 0.4.6",
"once_cell",
@@ -829,46 +752,43 @@ dependencies = [
[[package]]
name = "aws-sdk-kms"
-version = "0.28.0"
+version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "545335abd7c6ef7285d2972a67b9f8279ff5fec8bbb3ffc637fa436ba1e6e434"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-smithy-async 0.55.3",
- "aws-smithy-client",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-json 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
+checksum = "3c30f6fd5646b99d9b45ec3a0c22e67112c175b2383100c960d7ee39d96c8d96"
+dependencies = [
+ "aws-credential-types",
+ "aws-runtime",
+ "aws-smithy-async",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
"http 0.2.12",
- "regex",
- "tokio-stream",
- "tower",
+ "once_cell",
+ "regex-lite",
"tracing",
]
[[package]]
name = "aws-sdk-lambda"
-version = "1.43.0"
+version = "1.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd9e398f83bbd720e4bf785b9638f8c2189093da50edc2001966c53bf6d87b0c"
+checksum = "c1badb81ceafb6b329cd94a8d218e098b842c051da7821d66002f218106b073c"
dependencies = [
- "aws-credential-types 1.2.1",
+ "aws-credential-types",
"aws-runtime",
- "aws-smithy-async 1.2.1",
- "aws-smithy-eventstream 0.60.4",
- "aws-smithy-http 0.60.10",
- "aws-smithy-json 0.60.7",
+ "aws-smithy-async",
+ "aws-smithy-eventstream",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "aws-types 1.3.3",
- "bytes 1.7.1",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
"http 0.2.12",
"once_cell",
"regex-lite",
@@ -877,103 +797,76 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
-version = "0.28.0"
+version = "1.65.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fba197193cbb4bcb6aad8d99796b2291f36fa89562ded5d4501363055b0de89f"
+checksum = "d3ba2c5c0f2618937ce3d4a5ad574b86775576fa24006bcb3128c6e2cbf3c34e"
dependencies = [
- "aws-credential-types 0.55.3",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-sigv4 0.55.3",
- "aws-smithy-async 0.55.3",
+ "aws-credential-types",
+ "aws-runtime",
+ "aws-sigv4",
+ "aws-smithy-async",
"aws-smithy-checksums",
- "aws-smithy-client",
- "aws-smithy-eventstream 0.55.3",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-json 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-smithy-xml 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
+ "aws-smithy-eventstream",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types",
+ "aws-smithy-xml",
+ "aws-types",
+ "bytes 1.10.1",
+ "fastrand",
+ "hex",
+ "hmac",
"http 0.2.12",
"http-body 0.4.6",
+ "lru",
"once_cell",
"percent-encoding",
- "regex",
- "tokio-stream",
- "tower",
+ "regex-lite",
+ "sha2",
"tracing",
"url",
]
[[package]]
name = "aws-sdk-sesv2"
-version = "0.28.0"
+version = "1.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4891169a246b580136f4d3682c11a68b710bdc1027dd7774023fa651a87f10b6"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-smithy-async 0.55.3",
- "aws-smithy-client",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-json 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
- "http 0.2.12",
- "regex",
- "tokio-stream",
- "tower",
- "tracing",
-]
-
-[[package]]
-name = "aws-sdk-sso"
-version = "0.28.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8b812340d86d4a766b2ca73f740dfd47a97c2dff0c06c8517a16d88241957e4"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-smithy-async 0.55.3",
- "aws-smithy-client",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-json 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
+checksum = "3dfdd8eabbf8aea436830307108e249d9c60f7ecbd6a6953fda475d8985a8288"
+dependencies = [
+ "aws-credential-types",
+ "aws-runtime",
+ "aws-smithy-async",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
"http 0.2.12",
- "regex",
- "tokio-stream",
- "tower",
+ "once_cell",
+ "regex-lite",
"tracing",
]
[[package]]
name = "aws-sdk-sso"
-version = "1.40.0"
+version = "1.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5879bec6e74b648ce12f6085e7245417bc5f6d672781028384d2e494be3eb6d"
+checksum = "05ca43a4ef210894f93096039ef1d6fa4ad3edfabb3be92b80908b9f2e4b4eab"
dependencies = [
- "aws-credential-types 1.2.1",
+ "aws-credential-types",
"aws-runtime",
- "aws-smithy-async 1.2.1",
- "aws-smithy-http 0.60.10",
- "aws-smithy-json 0.60.7",
+ "aws-smithy-async",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "aws-types 1.3.3",
- "bytes 1.7.1",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
"http 0.2.12",
"once_cell",
"regex-lite",
@@ -982,20 +875,20 @@ dependencies = [
[[package]]
name = "aws-sdk-ssooidc"
-version = "1.41.0"
+version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ef4cd9362f638c22a3b959fd8df292e7e47fdf170270f86246b97109b5f2f7d"
+checksum = "abaf490c2e48eed0bb8e2da2fb08405647bd7f253996e0f93b981958ea0f73b0"
dependencies = [
- "aws-credential-types 1.2.1",
+ "aws-credential-types",
"aws-runtime",
- "aws-smithy-async 1.2.1",
- "aws-smithy-http 0.60.10",
- "aws-smithy-json 0.60.7",
+ "aws-smithy-async",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "aws-types 1.3.3",
- "bytes 1.7.1",
+ "aws-smithy-types",
+ "aws-types",
+ "bytes 1.10.1",
"http 0.2.12",
"once_cell",
"regex-lite",
@@ -1004,130 +897,61 @@ dependencies = [
[[package]]
name = "aws-sdk-sts"
-version = "0.28.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "265fac131fbfc188e5c3d96652ea90ecc676a934e3174eaaee523c6cec040b3b"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-smithy-async 0.55.3",
- "aws-smithy-client",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-json 0.55.3",
- "aws-smithy-query 0.55.3",
- "aws-smithy-types 0.55.3",
- "aws-smithy-xml 0.55.3",
- "aws-types 0.55.3",
- "bytes 1.7.1",
- "http 0.2.12",
- "regex",
- "tower",
- "tracing",
-]
-
-[[package]]
-name = "aws-sdk-sts"
-version = "1.40.0"
+version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b1e2735d2ab28b35ecbb5496c9d41857f52a0d6a0075bbf6a8af306045ea6f6"
+checksum = "b68fde0d69c8bfdc1060ea7da21df3e39f6014da316783336deff0a9ec28f4bf"
dependencies = [
- "aws-credential-types 1.2.1",
+ "aws-credential-types",
"aws-runtime",
- "aws-smithy-async 1.2.1",
- "aws-smithy-http 0.60.10",
- "aws-smithy-json 0.60.7",
- "aws-smithy-query 0.60.7",
+ "aws-smithy-async",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-json 0.61.3",
+ "aws-smithy-query",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "aws-smithy-xml 0.60.8",
- "aws-types 1.3.3",
+ "aws-smithy-types",
+ "aws-smithy-xml",
+ "aws-types",
"http 0.2.12",
"once_cell",
"regex-lite",
"tracing",
]
-[[package]]
-name = "aws-sig-auth"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b94acb10af0c879ecd5c7bdf51cda6679a0a4f4643ce630905a77673bfa3c61"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-sigv4 0.55.3",
- "aws-smithy-eventstream 0.55.3",
- "aws-smithy-http 0.55.3",
- "aws-types 0.55.3",
- "http 0.2.12",
- "tracing",
-]
-
[[package]]
name = "aws-sigv4"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d2ce6f507be68e968a33485ced670111d1cbad161ddbbab1e313c03d37d8f4c"
-dependencies = [
- "aws-smithy-eventstream 0.55.3",
- "aws-smithy-http 0.55.3",
- "bytes 1.7.1",
- "form_urlencoded",
- "hex",
- "hmac",
- "http 0.2.12",
- "once_cell",
- "percent-encoding",
- "regex",
- "sha2",
- "time",
- "tracing",
-]
-
-[[package]]
-name = "aws-sigv4"
-version = "1.2.3"
+version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5df1b0fa6be58efe9d4ccc257df0a53b89cd8909e86591a13ca54817c87517be"
+checksum = "69d03c3c05ff80d54ff860fe38c726f6f494c639ae975203a101335f223386db"
dependencies = [
- "aws-credential-types 1.2.1",
- "aws-smithy-eventstream 0.60.4",
- "aws-smithy-http 0.60.10",
+ "aws-credential-types",
+ "aws-smithy-eventstream",
+ "aws-smithy-http 0.62.0",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "bytes 1.7.1",
+ "aws-smithy-types",
+ "bytes 1.10.1",
+ "crypto-bigint 0.5.5",
"form_urlencoded",
"hex",
"hmac",
"http 0.2.12",
"http 1.1.0",
"once_cell",
+ "p256 0.11.1",
"percent-encoding",
+ "ring 0.17.8",
"sha2",
+ "subtle",
"time",
"tracing",
+ "zeroize",
]
[[package]]
name = "aws-smithy-async"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13bda3996044c202d75b91afeb11a9afae9db9a721c6a7a427410018e286b880"
-dependencies = [
- "futures-util",
- "pin-project-lite",
- "tokio 1.40.0",
- "tokio-stream",
-]
-
-[[package]]
-name = "aws-smithy-async"
-version = "1.2.1"
+version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62220bc6e97f946ddd51b5f1361f78996e704677afc518a4ff66b7a72ea1378c"
+checksum = "1e190749ea56f8c42bf15dd76c65e14f8f765233e6df9b0506d9d934ebef867c"
dependencies = [
"futures-util",
"pin-project-lite",
@@ -1136,13 +960,13 @@ dependencies = [
[[package]]
name = "aws-smithy-checksums"
-version = "0.55.3"
+version = "0.60.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07ed8b96d95402f3f6b8b57eb4e0e45ee365f78b1a924faf20ff6e97abf1eae6"
+checksum = "ba1a71073fca26775c8b5189175ea8863afb1c9ea2cceb02a5de5ad9dfbaa795"
dependencies = [
- "aws-smithy-http 0.55.3",
- "aws-smithy-types 0.55.3",
- "bytes 1.7.1",
+ "aws-smithy-http 0.60.12",
+ "aws-smithy-types",
+ "bytes 1.10.1",
"crc32c",
"crc32fast",
"hex",
@@ -1155,88 +979,51 @@ dependencies = [
"tracing",
]
-[[package]]
-name = "aws-smithy-client"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0a86aa6e21e86c4252ad6a0e3e74da9617295d8d6e374d552be7d3059c41cedd"
-dependencies = [
- "aws-smithy-async 0.55.3",
- "aws-smithy-http 0.55.3",
- "aws-smithy-http-tower",
- "aws-smithy-types 0.55.3",
- "bytes 1.7.1",
- "fastrand 1.9.0",
- "http 0.2.12",
- "http-body 0.4.6",
- "hyper 0.14.30",
- "hyper-rustls 0.23.2",
- "lazy_static",
- "pin-project-lite",
- "rustls 0.20.9",
- "tokio 1.40.0",
- "tower",
- "tracing",
-]
-
-[[package]]
-name = "aws-smithy-eventstream"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "460c8da5110835e3d9a717c61f5556b20d03c32a1dec57f8fc559b360f733bb8"
-dependencies = [
- "aws-smithy-types 0.55.3",
- "bytes 1.7.1",
- "crc32fast",
-]
-
[[package]]
name = "aws-smithy-eventstream"
-version = "0.60.4"
+version = "0.60.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6363078f927f612b970edf9d1903ef5cef9a64d1e8423525ebb1f0a1633c858"
+checksum = "7c45d3dddac16c5c59d553ece225a88870cf81b7b813c9cc17b78cf4685eac7a"
dependencies = [
- "aws-smithy-types 1.2.4",
- "bytes 1.7.1",
+ "aws-smithy-types",
+ "bytes 1.10.1",
"crc32fast",
]
[[package]]
name = "aws-smithy-http"
-version = "0.55.3"
+version = "0.60.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b3b693869133551f135e1f2c77cb0b8277d9e3e17feaf2213f735857c4f0d28"
+checksum = "7809c27ad8da6a6a68c454e651d4962479e81472aa19ae99e59f9aba1f9713cc"
dependencies = [
- "aws-smithy-eventstream 0.55.3",
- "aws-smithy-types 0.55.3",
- "bytes 1.7.1",
+ "aws-smithy-eventstream",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types",
+ "bytes 1.10.1",
"bytes-utils",
"futures-core",
"http 0.2.12",
"http-body 0.4.6",
- "hyper 0.14.30",
"once_cell",
"percent-encoding",
"pin-project-lite",
"pin-utils",
- "tokio 1.40.0",
- "tokio-util",
"tracing",
]
[[package]]
name = "aws-smithy-http"
-version = "0.60.10"
+version = "0.62.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "01dbcb6e2588fd64cfb6d7529661b06466419e4c54ed1c62d6510d2d0350a728"
+checksum = "c5949124d11e538ca21142d1fba61ab0a2a2c1bc3ed323cdb3e4b878bfb83166"
dependencies = [
- "aws-smithy-eventstream 0.60.4",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "bytes 1.7.1",
+ "aws-smithy-types",
+ "bytes 1.10.1",
"bytes-utils",
"futures-core",
"http 0.2.12",
+ "http 1.1.0",
"http-body 0.4.6",
"once_cell",
"percent-encoding",
@@ -1246,47 +1033,41 @@ dependencies = [
]
[[package]]
-name = "aws-smithy-http-tower"
-version = "0.55.3"
+name = "aws-smithy-http-client"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3ae4f6c5798a247fac98a867698197d9ac22643596dc3777f0c76b91917616b9"
+checksum = "0497ef5d53065b7cd6a35e9c1654bd1fefeae5c52900d91d1b188b0af0f29324"
dependencies = [
- "aws-smithy-http 0.55.3",
- "aws-smithy-types 0.55.3",
- "bytes 1.7.1",
+ "aws-smithy-async",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types",
+ "h2 0.4.6",
"http 0.2.12",
"http-body 0.4.6",
+ "hyper 0.14.30",
+ "hyper-rustls 0.24.2",
"pin-project-lite",
- "tower",
+ "rustls 0.21.12",
+ "tokio 1.40.0",
"tracing",
]
-[[package]]
-name = "aws-smithy-json"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "23f9f42fbfa96d095194a632fbac19f60077748eba536eb0b9fecc28659807f8"
-dependencies = [
- "aws-smithy-types 0.55.3",
-]
-
[[package]]
name = "aws-smithy-json"
version = "0.60.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4683df9469ef09468dad3473d129960119a0d3593617542b7d52086c8486f2d6"
dependencies = [
- "aws-smithy-types 1.2.4",
+ "aws-smithy-types",
]
[[package]]
-name = "aws-smithy-query"
-version = "0.55.3"
+name = "aws-smithy-json"
+version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "98819eb0b04020a1c791903533b638534ae6c12e2aceda3e6e6fba015608d51d"
+checksum = "92144e45819cae7dc62af23eac5a038a58aa544432d2102609654376a900bd07"
dependencies = [
- "aws-smithy-types 0.55.3",
- "urlencoding",
+ "aws-smithy-types",
]
[[package]]
@@ -1295,46 +1076,43 @@ version = "0.60.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2fbd61ceb3fe8a1cb7352e42689cec5335833cd9f94103a61e98f9bb61c64bb"
dependencies = [
- "aws-smithy-types 1.2.4",
+ "aws-smithy-types",
"urlencoding",
]
[[package]]
name = "aws-smithy-runtime"
-version = "1.7.1"
+version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d1ce695746394772e7000b39fe073095db6d45a862d0767dd5ad0ac0d7f8eb87"
+checksum = "f6328865e36c6fd970094ead6b05efd047d3a80ec5fc3be5e743910da9f2ebf8"
dependencies = [
- "aws-smithy-async 1.2.1",
- "aws-smithy-http 0.60.10",
+ "aws-smithy-async",
+ "aws-smithy-http 0.62.0",
+ "aws-smithy-http-client",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
- "bytes 1.7.1",
- "fastrand 2.1.1",
- "h2 0.3.26",
+ "aws-smithy-types",
+ "bytes 1.10.1",
+ "fastrand",
"http 0.2.12",
+ "http 1.1.0",
"http-body 0.4.6",
"http-body 1.0.1",
- "httparse",
- "hyper 0.14.30",
- "hyper-rustls 0.24.2",
"once_cell",
"pin-project-lite",
"pin-utils",
- "rustls 0.21.12",
"tokio 1.40.0",
"tracing",
]
[[package]]
name = "aws-smithy-runtime-api"
-version = "1.7.2"
+version = "1.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e086682a53d3aa241192aa110fa8dfce98f2f5ac2ead0de84d41582c7e8fdb96"
+checksum = "3da37cf5d57011cb1753456518ec76e31691f1f474b73934a284eb2a1c76510f"
dependencies = [
- "aws-smithy-async 1.2.1",
- "aws-smithy-types 1.2.4",
- "bytes 1.7.1",
+ "aws-smithy-async",
+ "aws-smithy-types",
+ "bytes 1.10.1",
"http 0.2.12",
"http 1.1.0",
"pin-project-lite",
@@ -1345,25 +1123,12 @@ dependencies = [
[[package]]
name = "aws-smithy-types"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "16a3d0bf4f324f4ef9793b86a1701d9700fbcdbd12a846da45eed104c634c6e8"
-dependencies = [
- "base64-simd",
- "itoa",
- "num-integer",
- "ryu",
- "time",
-]
-
-[[package]]
-name = "aws-smithy-types"
-version = "1.2.4"
+version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "273dcdfd762fae3e1650b8024624e7cd50e484e37abdab73a7a706188ad34543"
+checksum = "836155caafba616c0ff9b07944324785de2ab016141c3550bd1c07882f8cee8f"
dependencies = [
"base64-simd",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"bytes-utils",
"futures-core",
"http 0.2.12",
@@ -1384,48 +1149,23 @@ dependencies = [
[[package]]
name = "aws-smithy-xml"
-version = "0.55.3"
+version = "0.60.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1b9d12875731bd07e767be7baad95700c3137b56730ec9ddeedb52a5e5ca63b"
+checksum = "ab0b0166827aa700d3dc519f72f8b3a91c35d0b8d042dc5d643a91e6f80648fc"
dependencies = [
"xmlparser",
]
-[[package]]
-name = "aws-smithy-xml"
-version = "0.60.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d123fbc2a4adc3c301652ba8e149bf4bc1d1725affb9784eb20c953ace06bf55"
-dependencies = [
- "xmlparser",
-]
-
-[[package]]
-name = "aws-types"
-version = "0.55.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6dd209616cc8d7bfb82f87811a5c655dc97537f592689b18743bddf5dc5c4829"
-dependencies = [
- "aws-credential-types 0.55.3",
- "aws-smithy-async 0.55.3",
- "aws-smithy-client",
- "aws-smithy-http 0.55.3",
- "aws-smithy-types 0.55.3",
- "http 0.2.12",
- "rustc_version 0.4.1",
- "tracing",
-]
-
[[package]]
name = "aws-types"
-version = "1.3.3"
+version = "1.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5221b91b3e441e6675310829fd8984801b772cb1546ef6c0e54dec9f1ac13fef"
+checksum = "3873f8deed8927ce8d04487630dc9ff73193bab64742a61d050e57a68dec4125"
dependencies = [
- "aws-credential-types 1.2.1",
- "aws-smithy-async 1.2.1",
+ "aws-credential-types",
+ "aws-smithy-async",
"aws-smithy-runtime-api",
- "aws-smithy-types 1.2.4",
+ "aws-smithy-types",
"rustc_version 0.4.1",
"tracing",
]
@@ -1438,7 +1178,7 @@ checksum = "3a6c9af12842a67734c9a2e355436e5d03b22383ed60cf13cd0c18fbfe3dcbcf"
dependencies = [
"async-trait",
"axum-core",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-util",
"http 1.1.0",
"http-body 1.0.1",
@@ -1464,7 +1204,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a15c63fd72d41492dc4f497196f5da1fb04fb7529e631d73630d1b491e47a2e3"
dependencies = [
"async-trait",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-util",
"http 1.1.0",
"http-body 1.0.1",
@@ -1492,6 +1232,12 @@ dependencies = [
"rustc-demangle",
]
+[[package]]
+name = "base16ct"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce"
+
[[package]]
name = "base16ct"
version = "0.2.0"
@@ -1679,7 +1425,7 @@ dependencies = [
"proc-macro-crate 3.2.0",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"syn_derive",
]
@@ -1772,9 +1518,9 @@ dependencies = [
[[package]]
name = "bytes"
-version = "1.7.1"
+version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50"
+checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "bytes-utils"
@@ -1782,7 +1528,7 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"either",
]
@@ -1792,7 +1538,7 @@ version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74d80203ea6b29df88012294f62733de21cfeab47f17b41af3a38bc30a03ee72"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
]
[[package]]
@@ -1816,7 +1562,7 @@ dependencies = [
"router_env",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -1840,7 +1586,7 @@ dependencies = [
"semver 1.0.23",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -1994,7 +1740,7 @@ dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2028,7 +1774,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
"utoipa",
]
@@ -2054,7 +1800,7 @@ dependencies = [
"base64 0.22.1",
"base64-serde",
"blake3",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"common_enums",
"diesel",
"error-stack",
@@ -2086,7 +1832,7 @@ dependencies = [
"signal-hook-tokio",
"strum 0.26.3",
"test-case",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"tokio 1.40.0",
"url",
@@ -2427,6 +2173,18 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
+[[package]]
+name = "crypto-bigint"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef"
+dependencies = [
+ "generic-array",
+ "rand_core",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "crypto-bigint"
version = "0.5.5"
@@ -2478,7 +2236,7 @@ dependencies = [
"rust_decimal",
"rusty-money",
"serde",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -2505,7 +2263,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2553,7 +2311,7 @@ dependencies = [
"proc-macro2",
"quote",
"strsim 0.11.1",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2575,7 +2333,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"
dependencies = [
"darling_core 0.20.10",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2615,6 +2373,16 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
+[[package]]
+name = "der"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de"
+dependencies = [
+ "const-oid",
+ "zeroize",
+]
+
[[package]]
name = "der"
version = "0.7.9"
@@ -2702,7 +2470,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustc_version 0.4.1",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2737,7 +2505,7 @@ dependencies = [
"dsl_auto_type",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2768,7 +2536,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -2778,7 +2546,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "209c735641a413bc68c4923a9d6ad4bcb3ca306b794edaa7eb0b3228a99ffb25"
dependencies = [
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2801,7 +2569,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2859,7 +2627,7 @@ dependencies = [
"serde",
"serde_json",
"serde_path_to_error",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
]
@@ -2874,7 +2642,7 @@ dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -2883,18 +2651,30 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125"
+[[package]]
+name = "ecdsa"
+version = "0.14.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c"
+dependencies = [
+ "der 0.6.1",
+ "elliptic-curve 0.12.3",
+ "rfc6979 0.3.1",
+ "signature 1.6.4",
+]
+
[[package]]
name = "ecdsa"
version = "0.16.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [
- "der",
+ "der 0.7.9",
"digest",
- "elliptic-curve",
- "rfc6979",
- "signature",
- "spki",
+ "elliptic-curve 0.13.8",
+ "rfc6979 0.4.0",
+ "signature 2.2.0",
+ "spki 0.7.3",
]
[[package]]
@@ -2903,8 +2683,8 @@ version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
dependencies = [
- "pkcs8",
- "signature",
+ "pkcs8 0.10.2",
+ "signature 2.2.0",
]
[[package]]
@@ -2930,23 +2710,43 @@ dependencies = [
"serde",
]
+[[package]]
+name = "elliptic-curve"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3"
+dependencies = [
+ "base16ct 0.1.1",
+ "crypto-bigint 0.4.9",
+ "der 0.6.1",
+ "digest",
+ "ff 0.12.1",
+ "generic-array",
+ "group 0.12.1",
+ "pkcs8 0.9.0",
+ "rand_core",
+ "sec1 0.3.0",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "elliptic-curve"
version = "0.13.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
dependencies = [
- "base16ct",
- "crypto-bigint",
+ "base16ct 0.2.0",
+ "crypto-bigint 0.5.5",
"digest",
- "ff",
+ "ff 0.13.0",
"generic-array",
- "group",
+ "group 0.13.0",
"hkdf",
"pem-rfc7468",
- "pkcs8",
+ "pkcs8 0.10.2",
"rand_core",
- "sec1",
+ "sec1 0.7.3",
"subtle",
"zeroize",
]
@@ -3048,7 +2848,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
"utoipa",
]
@@ -3060,7 +2860,7 @@ dependencies = [
"quote",
"rustc-hash",
"strum 0.26.3",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -3114,7 +2914,7 @@ dependencies = [
"router_env",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -3124,12 +2924,12 @@ version = "0.1.0"
dependencies = [
"api_models",
"async-trait",
- "aws-config 0.55.3",
+ "aws-config",
"aws-sdk-kms",
"aws-sdk-s3",
"aws-sdk-sesv2",
- "aws-sdk-sts 0.28.0",
- "aws-smithy-client",
+ "aws-sdk-sts",
+ "aws-smithy-runtime",
"base64 0.22.1",
"common_utils",
"dyn-clone",
@@ -3146,7 +2946,7 @@ dependencies = [
"prost",
"router_env",
"serde",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"tonic",
"tonic-build",
@@ -3189,18 +2989,9 @@ dependencies = [
[[package]]
name = "fastrand"
-version = "1.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
-dependencies = [
- "instant",
-]
-
-[[package]]
-name = "fastrand"
-version = "2.1.1"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6"
+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "fdeflate"
@@ -3211,6 +3002,16 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "ff"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160"
+dependencies = [
+ "rand_core",
+ "subtle",
+]
+
[[package]]
name = "ff"
version = "0.13.0"
@@ -3269,6 +3070,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+[[package]]
+name = "foldhash"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f"
+
[[package]]
name = "foreign-types"
version = "0.3.2"
@@ -3301,7 +3108,7 @@ checksum = "b99c2b48934cd02a81032dd7428b7ae831a27794275bc94eba367418db8a9e55"
dependencies = [
"arc-swap",
"async-trait",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"bytes-utils",
"float-cmp",
"futures 0.3.30",
@@ -3376,9 +3183,9 @@ dependencies = [
[[package]]
name = "futures-core"
-version = "0.3.30"
+version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
@@ -3416,7 +3223,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -3559,13 +3366,24 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "group"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7"
+dependencies = [
+ "ff 0.12.1",
+ "rand_core",
+ "subtle",
+]
+
[[package]]
name = "group"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
dependencies = [
- "ff",
+ "ff 0.13.0",
"rand_core",
"subtle",
]
@@ -3576,7 +3394,7 @@ version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"fnv",
"futures-core",
"futures-sink",
@@ -3596,7 +3414,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205"
dependencies = [
"atomic-waker",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"fnv",
"futures-core",
"futures-sink",
@@ -3643,13 +3461,24 @@ dependencies = [
"allocator-api2",
]
+[[package]]
+name = "hashbrown"
+version = "0.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
[[package]]
name = "hashlink"
-version = "0.9.1"
+version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
+checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
dependencies = [
- "hashbrown 0.14.5",
+ "hashbrown 0.15.2",
]
[[package]]
@@ -3659,7 +3488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06683b93020a07e3dbcf5f8c0f6d40080d725bea7936fc01ad345c01b97dc270"
dependencies = [
"base64 0.21.7",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"headers-core",
"http 0.2.12",
"httpdate",
@@ -3767,7 +3596,7 @@ version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"fnv",
"itoa",
]
@@ -3778,7 +3607,7 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"fnv",
"itoa",
]
@@ -3789,7 +3618,7 @@ version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"http 0.2.12",
"pin-project-lite",
]
@@ -3800,7 +3629,7 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"http 1.1.0",
]
@@ -3810,7 +3639,7 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-util",
"http 1.1.0",
"http-body 1.0.1",
@@ -3844,7 +3673,7 @@ version = "0.14.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a152ddd61dfaec7273fe8419ab357f33aee0d914c5f4efbf0d96fa749eea5ec9"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-channel",
"futures-core",
"futures-util",
@@ -3864,11 +3693,11 @@ dependencies = [
[[package]]
name = "hyper"
-version = "1.4.1"
+version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50dfd22e0e76d0f662d429a5f80fcaf3855009297eab6a0a9f8543834744ba05"
+checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-channel",
"futures-util",
"h2 0.4.6",
@@ -3889,7 +3718,7 @@ version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca815a891b24fdfb243fa3239c86154392b0953ee584aa1a2a1f66d20cbe75cc"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures 0.3.30",
"headers",
"http 0.2.12",
@@ -3938,7 +3767,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3203a961e5c83b6f5498933e78b6b263e208c197b63e9c6c53cc82ffd3f63793"
dependencies = [
- "hyper 1.4.1",
+ "hyper 1.6.0",
"hyper-util",
"pin-project-lite",
"tokio 1.40.0",
@@ -3951,7 +3780,7 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"hyper 0.14.30",
"native-tls",
"tokio 1.40.0",
@@ -3964,9 +3793,9 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"http-body-util",
- "hyper 1.4.1",
+ "hyper 1.6.0",
"hyper-util",
"native-tls",
"tokio 1.40.0",
@@ -3980,12 +3809,12 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-channel",
"futures-util",
"http 1.1.0",
"http-body 1.0.1",
- "hyper 1.4.1",
+ "hyper 1.6.0",
"pin-project-lite",
"socket2",
"tokio 1.40.0",
@@ -4002,7 +3831,7 @@ dependencies = [
"api_models",
"async-trait",
"base64 0.22.1",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"cards",
"common_enums",
"common_types",
@@ -4049,7 +3878,7 @@ dependencies = [
"rustc-hash",
"serde",
"strum 0.25.0",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -4075,7 +3904,7 @@ dependencies = [
"serde",
"serde_json",
"serde_with",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"url",
"utoipa",
@@ -4088,7 +3917,7 @@ dependencies = [
"actix-web",
"api_models",
"async-trait",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"common_enums",
"common_utils",
"dyn-clone",
@@ -4104,7 +3933,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"url",
]
@@ -4247,7 +4076,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -4352,15 +4181,6 @@ dependencies = [
"cfb",
]
-[[package]]
-name = "instant"
-version = "0.1.13"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
-dependencies = [
- "cfg-if 1.0.0",
-]
-
[[package]]
name = "into-attr"
version = "0.1.1"
@@ -4440,7 +4260,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ea1dc4bf0fb4904ba83ffdb98af3d9c325274e92e6e295e4151e86c96363e04"
dependencies = [
"serde",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -4461,15 +4281,6 @@ dependencies = [
"either",
]
-[[package]]
-name = "itertools"
-version = "0.12.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
-dependencies = [
- "either",
-]
-
[[package]]
name = "itertools"
version = "0.13.0"
@@ -4507,7 +4318,7 @@ dependencies = [
"regex",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -4525,7 +4336,7 @@ dependencies = [
"regex",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -4588,7 +4399,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -4609,7 +4420,7 @@ dependencies = [
"convert_case 0.6.0",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -4637,7 +4448,7 @@ dependencies = [
"chumsky",
"email-encoding",
"email_address",
- "fastrand 2.1.1",
+ "fastrand",
"futures-util",
"hostname",
"httpdate",
@@ -4692,7 +4503,6 @@ version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
dependencies = [
- "cc",
"pkg-config",
"vcpkg",
]
@@ -4775,6 +4585,15 @@ version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
+[[package]]
+name = "lru"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
+dependencies = [
+ "hashbrown 0.15.2",
+]
+
[[package]]
name = "lru-cache"
version = "0.1.2"
@@ -4797,7 +4616,7 @@ dependencies = [
name = "masking"
version = "0.1.0"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"diesel",
"erased-serde 0.4.5",
"scylla",
@@ -4845,7 +4664,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -5030,7 +4849,7 @@ dependencies = [
"rustc_version 0.4.1",
"smallvec 1.13.2",
"tagptr",
- "thiserror",
+ "thiserror 1.0.63",
"triomphe",
"uuid",
]
@@ -5235,7 +5054,7 @@ dependencies = [
"kinded",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"urlencoding",
]
@@ -5255,7 +5074,7 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"sha2",
- "thiserror",
+ "thiserror 1.0.63",
"url",
]
@@ -5279,9 +5098,9 @@ dependencies = [
[[package]]
name = "once_cell"
-version = "1.19.0"
+version = "1.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc"
[[package]]
name = "oncemutex"
@@ -5322,7 +5141,7 @@ dependencies = [
"itertools 0.10.5",
"log",
"oauth2",
- "p256",
+ "p256 0.13.2",
"p384",
"rand",
"rsa",
@@ -5335,7 +5154,7 @@ dependencies = [
"serde_with",
"sha2",
"subtle",
- "thiserror",
+ "thiserror 1.0.63",
"url",
]
@@ -5345,12 +5164,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a62b025c3503d3d53eaba3b6f14adb955af9f69fc71141b4d030a4e5331f5d42"
dependencies = [
- "aws-credential-types 1.2.1",
- "aws-sigv4 1.2.3",
+ "aws-credential-types",
+ "aws-sigv4",
"aws-smithy-runtime-api",
- "aws-types 1.3.3",
+ "aws-types",
"base64 0.22.1",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"dyn-clone",
"lazy_static",
"percent-encoding",
@@ -5386,7 +5205,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -5417,7 +5236,7 @@ dependencies = [
"futures-sink",
"js-sys",
"pin-project-lite",
- "thiserror",
+ "thiserror 1.0.63",
"tracing",
]
@@ -5446,7 +5265,7 @@ dependencies = [
"opentelemetry-proto",
"opentelemetry_sdk",
"prost",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"tonic",
]
@@ -5477,7 +5296,7 @@ dependencies = [
"opentelemetry",
"percent-encoding",
"rand",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"tokio-stream",
]
@@ -5513,14 +5332,25 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
+[[package]]
+name = "p256"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594"
+dependencies = [
+ "ecdsa 0.14.8",
+ "elliptic-curve 0.12.3",
+ "sha2",
+]
+
[[package]]
name = "p256"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
dependencies = [
- "ecdsa",
- "elliptic-curve",
+ "ecdsa 0.16.9",
+ "elliptic-curve 0.13.8",
"primeorder",
"sha2",
]
@@ -5531,8 +5361,8 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70786f51bcc69f6a4c0360e063a4cac5419ef7c5cd5b3c99ad70f3be5ba79209"
dependencies = [
- "ecdsa",
- "elliptic-curve",
+ "ecdsa 0.16.9",
+ "elliptic-curve 0.13.8",
"primeorder",
"sha2",
]
@@ -5673,7 +5503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd53dff83f26735fdc1ca837098ccf133605d794cdae66acfc2bfac3ec809d95"
dependencies = [
"memchr",
- "thiserror",
+ "thiserror 1.0.63",
"ucd-trie",
]
@@ -5697,7 +5527,7 @@ dependencies = [
"pest_meta",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -5768,7 +5598,7 @@ dependencies = [
"bincode",
"either",
"fnv",
- "itertools 0.12.1",
+ "itertools 0.11.0",
"lazy_static",
"nom",
"quick-xml",
@@ -5777,7 +5607,7 @@ dependencies = [
"serde",
"serde_derive",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -5797,7 +5627,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -5818,9 +5648,19 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [
- "der",
- "pkcs8",
- "spki",
+ "der 0.7.9",
+ "pkcs8 0.10.2",
+ "spki 0.7.3",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba"
+dependencies = [
+ "der 0.6.1",
+ "spki 0.6.0",
]
[[package]]
@@ -5829,8 +5669,8 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [
- "der",
- "spki",
+ "der 0.7.9",
+ "spki 0.7.3",
]
[[package]]
@@ -5873,7 +5713,7 @@ version = "0.1.0"
dependencies = [
"api_models",
"async-trait",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"common_enums",
"common_utils",
"error-stack",
@@ -5883,7 +5723,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -5930,7 +5770,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e"
dependencies = [
"proc-macro2",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -5939,7 +5779,7 @@ version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
dependencies = [
- "elliptic-curve",
+ "elliptic-curve 0.13.8",
]
[[package]]
@@ -5987,9 +5827,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
-version = "1.0.86"
+version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
+checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
dependencies = [
"unicode-ident",
]
@@ -6020,7 +5860,7 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b2ecbe40f08db5c006b5764a2645f7f3f141ce756412ac9e1dd6087e6d32995"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"prost-derive",
]
@@ -6030,7 +5870,7 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"heck 0.5.0",
"itertools 0.13.0",
"log",
@@ -6041,7 +5881,7 @@ dependencies = [
"prost",
"prost-types",
"regex",
- "syn 2.0.77",
+ "syn 2.0.100",
"tempfile",
]
@@ -6055,7 +5895,7 @@ dependencies = [
"itertools 0.13.0",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -6281,7 +6121,7 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c31deddf734dc0a39d3112e73490e88b61a05e83e074d211f348404cee4d2c6"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"bytes-utils",
"cookie-factory",
"crc16",
@@ -6298,7 +6138,7 @@ dependencies = [
"fred",
"futures 0.3.30",
"serde",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"tokio-stream",
"tracing",
@@ -6407,7 +6247,7 @@ checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62"
dependencies = [
"async-compression",
"base64 0.21.7",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"encoding_rs",
"futures-core",
"futures-util",
@@ -6454,13 +6294,13 @@ checksum = "f8f4955649ef5c38cc7f9e8aa41761d48fb9677197daea9984dc54f56aad5e63"
dependencies = [
"async-compression",
"base64 0.22.1",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-core",
"futures-util",
"http 1.1.0",
"http-body 1.0.1",
"http-body-util",
- "hyper 1.4.1",
+ "hyper 1.6.0",
"hyper-tls 0.6.0",
"hyper-util",
"ipnet",
@@ -6487,6 +6327,17 @@ dependencies = [
"windows-registry",
]
+[[package]]
+name = "rfc6979"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb"
+dependencies = [
+ "crypto-bigint 0.4.9",
+ "hmac",
+ "zeroize",
+]
+
[[package]]
name = "rfc6979"
version = "0.4.0"
@@ -6535,7 +6386,7 @@ checksum = "9008cd6385b9e161d8229e1f6549dd23c3d022f132a2ea37ac3a10ac4935779b"
dependencies = [
"bitvec",
"bytecheck",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"hashbrown 0.12.3",
"ptr_meta",
"rend",
@@ -6599,7 +6450,7 @@ dependencies = [
"base64 0.22.1",
"bb8",
"blake3",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"cards",
"clap",
"common_enums",
@@ -6676,7 +6527,7 @@ dependencies = [
"strum 0.26.3",
"tera",
"test_utils",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"tokio 1.40.0",
"totp-rs",
@@ -6705,7 +6556,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.26.3",
- "syn 2.0.77",
+ "syn 2.0.100",
"utoipa",
]
@@ -6756,10 +6607,10 @@ dependencies = [
"num-integer",
"num-traits",
"pkcs1",
- "pkcs8",
+ "pkcs8 0.10.2",
"rand_core",
- "signature",
- "spki",
+ "signature 2.2.0",
+ "spki 0.7.3",
"subtle",
"zeroize",
]
@@ -6790,7 +6641,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yml",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -6833,7 +6684,7 @@ checksum = "b082d80e3e3cc52b2ed634388d436fe1f4de6af5786cc2de9ba9737527bdf555"
dependencies = [
"arrayvec",
"borsh",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"num-traits",
"rand",
"rkyv",
@@ -6888,14 +6739,14 @@ checksum = "e9c02e25271068de581e03ac3bb44db60165ff1a10d92b9530192ccb898bc706"
dependencies = [
"anyhow",
"async-trait",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"http 0.2.12",
"reqwest 0.11.27",
"rustify_derive",
"serde",
"serde_json",
"serde_urlencoded",
- "thiserror",
+ "thiserror 1.0.63",
"tracing",
"url",
]
@@ -6960,7 +6811,7 @@ dependencies = [
"log",
"ring 0.17.8",
"rustls-pki-types",
- "rustls-webpki 0.102.7",
+ "rustls-webpki 0.102.8",
"subtle",
"zeroize",
]
@@ -6998,9 +6849,9 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
-version = "1.8.0"
+version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc0a2ce646f8655401bb81e7927b812614bd5d91dbc968696be50603510fcaf0"
+checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
[[package]]
name = "rustls-webpki"
@@ -7014,9 +6865,9 @@ dependencies = [
[[package]]
name = "rustls-webpki"
-version = "0.102.7"
+version = "0.102.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "84678086bd54edf2b415183ed7a94d0efb049f1b646a33e22a36f3794be6ae56"
+checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
dependencies = [
"ring 0.17.8",
"rustls-pki-types",
@@ -7111,7 +6962,7 @@ dependencies = [
"serde_json",
"storage_impl",
"strum 0.26.3",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"tokio 1.40.0",
"uuid",
@@ -7141,7 +6992,7 @@ dependencies = [
"arc-swap",
"async-trait",
"byteorder",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"chrono",
"dashmap",
"futures 0.3.30",
@@ -7157,7 +7008,7 @@ dependencies = [
"smallvec 1.13.2",
"snap",
"socket2",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"tracing",
"uuid",
@@ -7170,12 +7021,12 @@ source = "git+https://github.com/juspay/scylla-rust-driver.git?rev=5700aa2847b25
dependencies = [
"async-trait",
"byteorder",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"lz4_flex",
"scylla-macros",
"snap",
"stable_deref_trait",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"uuid",
"yoke",
@@ -7189,7 +7040,7 @@ dependencies = [
"darling 0.20.10",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -7204,16 +7055,30 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
+[[package]]
+name = "sec1"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928"
+dependencies = [
+ "base16ct 0.1.1",
+ "der 0.6.1",
+ "generic-array",
+ "pkcs8 0.9.0",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "sec1"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
dependencies = [
- "base16ct",
- "der",
+ "base16ct 0.2.0",
+ "der 0.7.9",
"generic-array",
- "pkcs8",
+ "pkcs8 0.10.2",
"subtle",
"zeroize",
]
@@ -7233,9 +7098,9 @@ dependencies = [
[[package]]
name = "security-framework-sys"
-version = "2.11.1"
+version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf"
+checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32"
dependencies = [
"core-foundation-sys",
"libc",
@@ -7314,7 +7179,7 @@ checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -7357,7 +7222,7 @@ checksum = "0431a35568651e363364210c91983c1da5eb29404d9f0928b67d4ebcfa7d330c"
dependencies = [
"percent-encoding",
"serde",
- "thiserror",
+ "thiserror 1.0.63",
]
[[package]]
@@ -7368,7 +7233,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -7419,7 +7284,7 @@ dependencies = [
"darling 0.20.10",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -7461,7 +7326,7 @@ checksum = "82fe9db325bcef1fbcde82e078a5cc4efdf787e96b3b9cf45b50b529f2083d67"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -7532,6 +7397,16 @@ dependencies = [
"tokio 1.40.0",
]
+[[package]]
+name = "signature"
+version = "1.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c"
+dependencies = [
+ "digest",
+ "rand_core",
+]
+
[[package]]
name = "signature"
version = "2.2.0"
@@ -7562,7 +7437,7 @@ checksum = "adc4e5204eb1910f40f9cfa375f6f05b68c3abac4b6fd879c8ff5e7ae8a0a085"
dependencies = [
"num-bigint",
"num-traits",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -7648,29 +7523,29 @@ dependencies = [
[[package]]
name = "spki"
-version = "0.7.3"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b"
dependencies = [
"base64ct",
- "der",
+ "der 0.6.1",
]
[[package]]
-name = "sqlformat"
-version = "0.2.4"
+name = "spki"
+version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f895e3734318cc55f1fe66258926c9b910c124d47520339efecbb6c59cec7c1f"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [
- "nom",
- "unicode_categories",
+ "base64ct",
+ "der 0.7.9",
]
[[package]]
name = "sqlx"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93334716a037193fac19df402f8571269c84a00852f6a7066b5d2616dcd64d3e"
+checksum = "4410e73b3c0d8442c5f99b425d7a435b5ee0ae4167b3196771dd3f7a01be745f"
dependencies = [
"sqlx-core",
"sqlx-macros",
@@ -7681,39 +7556,33 @@ dependencies = [
[[package]]
name = "sqlx-core"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4d8060b456358185f7d50c55d9b5066ad956956fddec42ee2e8567134a8936e"
+checksum = "6a007b6936676aa9ab40207cde35daab0a04b823be8ae004368c0793b96a61e0"
dependencies = [
- "atoi",
"bigdecimal",
- "byteorder",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"crc",
"crossbeam-queue 0.3.11",
"either",
"event-listener",
- "futures-channel",
"futures-core",
"futures-intrusive",
"futures-io",
"futures-util",
- "hashbrown 0.14.5",
+ "hashbrown 0.15.2",
"hashlink",
- "hex",
"indexmap 2.5.0",
"log",
"memchr",
"native-tls",
"once_cell",
- "paste",
"percent-encoding",
"serde",
"serde_json",
"sha2",
"smallvec 1.13.2",
- "sqlformat",
- "thiserror",
+ "thiserror 2.0.12",
"time",
"tokio 1.40.0",
"tokio-stream",
@@ -7723,22 +7592,22 @@ dependencies = [
[[package]]
name = "sqlx-macros"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cac0692bcc9de3b073e8d747391827297e075c7710ff6276d9f7a1f3d58c6657"
+checksum = "3112e2ad78643fef903618d78cf0aec1cb3134b019730edb039b69eaf531f310"
dependencies = [
"proc-macro2",
"quote",
"sqlx-core",
"sqlx-macros-core",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
name = "sqlx-macros-core"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1804e8a7c7865599c9c79be146dc8a9fd8cc86935fa641d3ea58e5f0688abaa5"
+checksum = "4e9f90acc5ab146a99bf5061a7eb4976b573f560bc898ef3bf8435448dd5e7ad"
dependencies = [
"dotenvy",
"either",
@@ -7754,7 +7623,7 @@ dependencies = [
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
- "syn 2.0.77",
+ "syn 2.0.100",
"tempfile",
"tokio 1.40.0",
"url",
@@ -7762,16 +7631,16 @@ dependencies = [
[[package]]
name = "sqlx-mysql"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64bb4714269afa44aef2755150a0fc19d756fb580a67db8885608cf02f47d06a"
+checksum = "4560278f0e00ce64938540546f59f590d60beee33fffbd3b9cd47851e5fff233"
dependencies = [
"atoi",
"base64 0.22.1",
"bigdecimal",
"bitflags 2.6.0",
"byteorder",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"crc",
"digest",
"dotenvy",
@@ -7798,7 +7667,7 @@ dependencies = [
"smallvec 1.13.2",
"sqlx-core",
"stringprep",
- "thiserror",
+ "thiserror 2.0.12",
"time",
"tracing",
"whoami",
@@ -7806,9 +7675,9 @@ dependencies = [
[[package]]
name = "sqlx-postgres"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6fa91a732d854c5d7726349bb4bb879bb9478993ceb764247660aee25f67c2f8"
+checksum = "c5b98a57f363ed6764d5b3a12bfedf62f07aa16e1856a7ddc2a0bb190a959613"
dependencies = [
"atoi",
"base64 0.22.1",
@@ -7820,7 +7689,6 @@ dependencies = [
"etcetera",
"futures-channel",
"futures-core",
- "futures-io",
"futures-util",
"hex",
"hkdf",
@@ -7839,7 +7707,7 @@ dependencies = [
"smallvec 1.13.2",
"sqlx-core",
"stringprep",
- "thiserror",
+ "thiserror 2.0.12",
"time",
"tracing",
"whoami",
@@ -7847,9 +7715,9 @@ dependencies = [
[[package]]
name = "sqlx-sqlite"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d5b2cf34a45953bfd3daaf3db0f7a7878ab9b7a6b91b422d24a7a9e4c857b680"
+checksum = "f85ca71d3a5b24e64e1d08dd8fe36c6c95c339a896cc33068148906784620540"
dependencies = [
"atoi",
"flume",
@@ -7902,7 +7770,7 @@ dependencies = [
"async-bb8-diesel",
"async-trait",
"bb8",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"common_enums",
"common_utils",
"config",
@@ -7921,7 +7789,7 @@ dependencies = [
"router_env",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
]
@@ -7985,7 +7853,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustversion",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -7998,7 +7866,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustversion",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8020,9 +7888,9 @@ dependencies = [
[[package]]
name = "syn"
-version = "2.0.77"
+version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed"
+checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
@@ -8038,7 +7906,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8076,7 +7944,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8119,7 +7987,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64"
dependencies = [
"cfg-if 1.0.0",
- "fastrand 2.1.1",
+ "fastrand",
"once_cell",
"rustix",
"windows-sys 0.59.0",
@@ -8165,7 +8033,7 @@ dependencies = [
"cfg-if 1.0.0",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8176,7 +8044,7 @@ checksum = "5c89e72a01ed4c579669add59014b9a524d609c0c88c6a585ce37485879f6ffb"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"test-case-core",
]
@@ -8222,7 +8090,7 @@ dependencies = [
"serde_repr",
"stringmatch",
"thirtyfour-macros",
- "thiserror",
+ "thiserror 1.0.63",
"tokio 1.40.0",
"url",
"urlparse",
@@ -8236,7 +8104,7 @@ checksum = "b72d056365e368fc57a56d0cec9e41b02fb4a3474a61c8735262b1cfebe67425"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8245,7 +8113,16 @@ version = "1.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724"
dependencies = [
- "thiserror-impl",
+ "thiserror-impl 1.0.63",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
+dependencies = [
+ "thiserror-impl 2.0.12",
]
[[package]]
@@ -8256,7 +8133,18 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.100",
]
[[package]]
@@ -8377,7 +8265,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2b070231665d27ad9ec9b8df639893f46727666c6767db40317fbe920a5d998"
dependencies = [
"backtrace",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"libc",
"mio 1.0.2",
"parking_lot 0.12.3",
@@ -8449,7 +8337,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8617,7 +8505,7 @@ version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1"
dependencies = [
- "bytes 1.7.1",
+ "bytes 1.10.1",
"futures-core",
"futures-sink",
"pin-project-lite",
@@ -8703,12 +8591,12 @@ dependencies = [
"async-trait",
"axum",
"base64 0.22.1",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"h2 0.4.6",
"http 1.1.0",
"http-body 1.0.1",
"http-body-util",
- "hyper 1.4.1",
+ "hyper 1.6.0",
"hyper-timeout",
"hyper-util",
"percent-encoding",
@@ -8733,7 +8621,7 @@ dependencies = [
"proc-macro2",
"prost-build",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -8842,7 +8730,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3566e8ce28cc0a3fe42519fc80e6b4c943cc4c8cef275620eb8dac2d3d4e06cf"
dependencies = [
"crossbeam-channel",
- "thiserror",
+ "thiserror 1.0.63",
"time",
"tracing-subscriber",
]
@@ -8855,7 +8743,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -9088,12 +8976,6 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a"
-[[package]]
-name = "unicode_categories"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
-
[[package]]
name = "unidecode"
version = "0.3.0"
@@ -9114,12 +8996,12 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
-version = "2.5.2"
+version = "2.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c"
+checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60"
dependencies = [
"form_urlencoded",
- "idna 0.5.0",
+ "idna 1.0.3",
"percent-encoding",
"serde",
]
@@ -9175,7 +9057,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -9215,7 +9097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb996bb053adadc767f8b0bda2a80bc2b67d24fe89f2b959ae919e200d79a19"
dependencies = [
"async-trait",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"derive_builder",
"http 0.2.12",
"reqwest 0.11.27",
@@ -9223,7 +9105,7 @@ dependencies = [
"rustify_derive",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.63",
"tracing",
"url",
]
@@ -9329,7 +9211,7 @@ dependencies = [
"log",
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"wasm-bindgen-shared",
]
@@ -9363,7 +9245,7 @@ checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
@@ -9401,7 +9283,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9973cb72c8587d5ad5efdb91e663d36177dc37725e6c90ca86c626b0cc45c93f"
dependencies = [
"base64 0.13.1",
- "bytes 1.7.1",
+ "bytes 1.10.1",
"cookie 0.16.2",
"http 0.2.12",
"log",
@@ -9729,7 +9611,7 @@ dependencies = [
"futures 0.3.30",
"http 1.1.0",
"http-body-util",
- "hyper 1.4.1",
+ "hyper 1.6.0",
"hyper-util",
"log",
"once_cell",
@@ -9784,7 +9666,7 @@ dependencies = [
"nom",
"oid-registry",
"rusticata-macros",
- "thiserror",
+ "thiserror 1.0.63",
"time",
]
@@ -9823,7 +9705,7 @@ checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"synstructure 0.13.1",
]
@@ -9845,7 +9727,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
@@ -9865,7 +9747,7 @@ checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
"synstructure 0.13.1",
]
@@ -9894,7 +9776,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.77",
+ "syn 2.0.100",
]
[[package]]
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index 34732c55e4e..ab63e47d8f3 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -26,9 +26,9 @@ currency_conversion = { version = "0.1.0", path = "../currency_conversion" }
#Third Party dependencies
actix-web = "4.5.1"
async-trait = "0.1.79"
-aws-config = { version = "1.1.9", features = ["behavior-version-latest"] }
-aws-sdk-lambda = { version = "1.18.0" }
-aws-smithy-types = { version = "1.1.8" }
+aws-config = { version = "1.5.10", features = ["behavior-version-latest"] }
+aws-sdk-lambda = { version = "1.60.0" }
+aws-smithy-types = { version = "1.3.0" }
bigdecimal = { version = "0.4.5", features = ["serde"] }
error-stack = "0.4.1"
futures = "0.3.30"
@@ -38,7 +38,7 @@ reqwest = { version = "0.11.27", features = ["serde_json"] }
rust_decimal = "1.35"
serde = { version = "1.0.197", features = ["derive", "rc"] }
serde_json = "1.0.115"
-sqlx = { version = "0.8.2", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] }
+sqlx = { version = "0.8.3", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] }
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index e617dbe8351..ebab30eec70 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -17,12 +17,12 @@ dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-
[dependencies]
async-trait = "0.1.79"
-aws-config = { version = "0.55.3", optional = true }
-aws-sdk-kms = { version = "0.28.0", optional = true }
-aws-sdk-s3 = { version = "0.28.0", optional = true }
-aws-sdk-sesv2 = "0.28.0"
-aws-sdk-sts = "0.28.0"
-aws-smithy-client = "0.55.3"
+aws-config = { version = "1.5.10", optional = true, features = ["behavior-version-latest"] }
+aws-sdk-kms = { version = "1.51.0", optional = true }
+aws-sdk-sesv2 = "1.57.0"
+aws-sdk-sts = "1.51.0"
+aws-sdk-s3 = { version = "1.65.0", optional = true }
+aws-smithy-runtime = "1.8.0"
base64 = "0.22.0"
dyn-clone = "1.0.17"
error-stack = "0.4.1"
diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs
index a98b03c0b54..82a0da7cb9b 100644
--- a/crates/external_services/src/email.rs
+++ b/crates/external_services/src/email.rs
@@ -193,4 +193,8 @@ pub enum EmailError {
/// The expected feature is not implemented
#[error("Feature not implemented")]
NotImplemented,
+
+ /// An error occurred when building email content.
+ #[error("Error building email content")]
+ ContentBuildFailure,
}
diff --git a/crates/external_services/src/email/ses.rs b/crates/external_services/src/email/ses.rs
index f9dcc8f26ad..f8e941b57b5 100644
--- a/crates/external_services/src/email/ses.rs
+++ b/crates/external_services/src/email/ses.rs
@@ -7,6 +7,7 @@ use aws_sdk_sesv2::{
Client,
};
use aws_sdk_sts::config::Credentials;
+use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
use common_utils::{errors::CustomResult, pii};
use error_stack::{report, ResultExt};
use hyper::Uri;
@@ -53,7 +54,7 @@ impl SESConfig {
pub enum AwsSesError {
/// An error occurred in the SDK while sending email.
#[error("Failed to Send Email {0:?}")]
- SendingFailure(aws_smithy_client::SdkError<SendEmailError>),
+ SendingFailure(aws_sdk_sesv2::error::SdkError<SendEmailError>),
/// Configuration variable is missing to construct the email client
#[error("Missing configuration variable {0}")]
@@ -131,29 +132,13 @@ impl AwsSes {
)?;
let credentials = Credentials::new(
- creds
- .access_key_id()
- .ok_or(
- report!(AwsSesError::TemporaryCredentialsMissing(format!(
- "{role:?}"
- )))
- .attach_printable("Access Key ID not found"),
- )?
- .to_owned(),
- creds
- .secret_access_key()
- .ok_or(
- report!(AwsSesError::TemporaryCredentialsMissing(format!(
- "{role:?}"
- )))
- .attach_printable("Secret Access Key not found"),
- )?
- .to_owned(),
- creds.session_token().map(|s| s.to_owned()),
- creds.expiration().and_then(|dt| {
- SystemTime::UNIX_EPOCH
- .checked_add(Duration::from_nanos(u64::try_from(dt.as_nanos()).ok()?))
- }),
+ creds.access_key_id(),
+ creds.secret_access_key(),
+ Some(creds.session_token().to_owned()),
+ u64::try_from(creds.expiration().as_nanos())
+ .ok()
+ .map(Duration::from_nanos)
+ .and_then(|val| SystemTime::UNIX_EPOCH.checked_add(val)),
"custom_provider",
);
@@ -176,15 +161,11 @@ impl AwsSes {
) -> CustomResult<aws_config::ConfigLoader, AwsSesError> {
let region_provider = Region::new(region);
let mut config = aws_config::from_env().region(region_provider);
+
if let Some(proxy_url) = proxy_url {
let proxy_connector = Self::get_proxy_connector(proxy_url)?;
- let provider_config = aws_config::provider_config::ProviderConfig::default()
- .with_tcp_connector(proxy_connector.clone());
- let http_connector =
- aws_smithy_client::hyper_ext::Adapter::builder().build(proxy_connector);
- config = config
- .configure(provider_config)
- .http_connector(http_connector);
+ let http_client = HyperClientBuilder::new().build(proxy_connector);
+ config = config.http_client(http_client);
};
Ok(config)
}
@@ -218,7 +199,8 @@ impl EmailClient for AwsSes {
Content::builder()
.data(intermediate_string.into_inner())
.charset("UTF-8")
- .build(),
+ .build()
+ .change_context(EmailError::ContentBuildFailure)?,
)
.build();
@@ -250,7 +232,12 @@ impl EmailClient for AwsSes {
EmailContent::builder()
.simple(
Message::builder()
- .subject(Content::builder().data(subject).build())
+ .subject(
+ Content::builder()
+ .data(subject)
+ .build()
+ .change_context(EmailError::ContentBuildFailure)?,
+ )
.body(body)
.build(),
)
diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs
index 86d1c0f0efa..28d307da33b 100644
--- a/crates/external_services/src/file_storage/aws_s3.rs
+++ b/crates/external_services/src/file_storage/aws_s3.rs
@@ -142,15 +142,15 @@ impl FileStorageInterface for AwsFileStorageClient {
enum AwsS3StorageError {
/// Error indicating that file upload to S3 failed.
#[error("File upload to S3 failed: {0:?}")]
- UploadFailure(aws_smithy_client::SdkError<PutObjectError>),
+ UploadFailure(aws_sdk_s3::error::SdkError<PutObjectError>),
/// Error indicating that file retrieval from S3 failed.
#[error("File retrieve from S3 failed: {0:?}")]
- RetrieveFailure(aws_smithy_client::SdkError<GetObjectError>),
+ RetrieveFailure(aws_sdk_s3::error::SdkError<GetObjectError>),
/// Error indicating that file deletion from S3 failed.
#[error("File delete from S3 failed: {0:?}")]
- DeleteFailure(aws_smithy_client::SdkError<DeleteObjectError>),
+ DeleteFailure(aws_sdk_s3::error::SdkError<DeleteObjectError>),
/// Unknown error occurred.
#[error("Unknown error occurred: {0:?}")]
|
2024-03-26T07:34:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [x] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR updates rust aws dependencies to their latest version
### 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)?
-->
Deployed the branch in custom pod. Application deployed successfully hence kms feature works fine.
Tested email feature too.
```
curl --location 'https://http://localhost:8080/user/signup_with_merchant_id' \
--header 'Content-Type: application/json' \
--header 'api-key: abc' \
--data-raw '{
"email": "test_email@gmail.com",
"password": "Test@123",
"company_name": "test_comp2",
"name": "test_merchant1"
}'
```

## Checklist
<!-- Put an `x` in 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
|
4b922e54847c2c0cc0ecf1c17ae84a3db075b989
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4171
|
Bug: chore: address Rust 1.77 clippy lints
Address the clippy lints occurring due to new rust version 1.77
See #3391 for more information.
|
diff --git a/add_connector.md b/add_connector.md
index ac9d3f8d847..96724cb1b01 100644
--- a/add_connector.md
+++ b/add_connector.md
@@ -514,28 +514,23 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
}
```
-- `get_request_body` method calls transformers where hyperswitch payment request data is transformed into connector payment request. For constructing the request body have a function `log_and_get_request_body` that allows generic argument which is the struct that is passed as the body for connector integration, and a function that can be use to encode it into String. We log the request in this function, as the struct will be intact and the masked values will be masked.
+- `get_request_body` method calls transformers where hyperswitch payment request data is transformed into connector payment request. If the conversion and construction processes are successful, the function wraps the constructed connector_req in a Box and returns it as `RequestContent::Json`. The `RequestContent` enum defines different types of request content that can be sent. It includes variants for JSON, form-urlencoded, XML, raw bytes, and potentially other formats.
```rust
fn get_request_body(
- &self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_router_data = checkout::CheckoutRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount,
- req,
- ))?;
- let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?;
- let checkout_req = types::RequestBody::log_and_get_request_body(
- &connector_req,
- utils::Encode::encode_to_string_of_json,
- )
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- Ok(Some(checkout_req))
- }
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_router_data = checkout::CheckoutRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
```
- `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters.
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index 3dbab96408c..b1a708f7a08 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -35,9 +35,6 @@ pub mod date_time {
},
OffsetDateTime, PrimitiveDateTime,
};
- /// Struct to represent milliseconds in time sensitive data fields
- #[derive(Debug)]
- pub struct Milliseconds(i32);
/// Enum to represent date formats
#[derive(Debug)]
diff --git a/crates/common_utils/src/request.rs b/crates/common_utils/src/request.rs
index dfd890df795..47f280bc577 100644
--- a/crates/common_utils/src/request.rs
+++ b/crates/common_utils/src/request.rs
@@ -1,10 +1,6 @@
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(
@@ -64,6 +60,18 @@ pub enum RequestContent {
RawBytes(Vec<u8>),
}
+impl RequestContent {
+ pub fn get_inner_value(&self) -> Secret<String> {
+ match self {
+ Self::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(),
+ Self::FormUrlEncoded(i) => serde_urlencoded::to_string(i).unwrap_or_default().into(),
+ Self::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(),
+ Self::FormData(_) => String::new().into(),
+ Self::RawBytes(_) => String::new().into(),
+ }
+ }
+}
+
impl Request {
pub fn new(method: Method, url: &str) -> Self {
Self {
@@ -176,33 +184,3 @@ impl Default for RequestBuilder {
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: RequestContent) -> Secret<String> {
- match request_body {
- RequestContent::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(),
- RequestContent::FormUrlEncoded(i) => {
- serde_urlencoded::to_string(&i).unwrap_or_default().into()
- }
- RequestContent::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(),
- RequestContent::FormData(_) => String::new().into(),
- RequestContent::RawBytes(_) => String::new().into(),
- }
- }
-}
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index 74fa75a2751..0c6aaa5922f 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -190,27 +190,6 @@ impl From<ProcessTrackerUpdate> for ProcessTrackerUpdateInternal {
}
}
-#[allow(dead_code)]
-pub struct SchedulerOptions {
- looper_interval: common_utils::date_time::Milliseconds,
- db_name: String,
- cache_name: String,
- schema_name: String,
- cache_expiry: i32,
- runners: Vec<String>,
- fetch_limit: i32,
- fetch_limit_product_factor: i32,
- query_order: String,
-}
-
-#[derive(Debug, Clone)]
-#[allow(dead_code)]
-pub struct ProcessData {
- db_name: String,
- cache_name: String,
- process_tracker: ProcessTracker,
-}
-
#[derive(
serde::Serialize,
serde::Deserialize,
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs
index fefc80f806c..aac441201eb 100644
--- a/crates/router/src/connector/bankofamerica.rs
+++ b/crates/router/src/connector/bankofamerica.rs
@@ -140,11 +140,7 @@ where
.chars()
.skip(base_url.len() - 1)
.collect();
- let sha256 = self.generate_digest(
- types::RequestBody::get_inner_value(boa_req)
- .expose()
- .as_bytes(),
- );
+ let sha256 = self.generate_digest(boa_req.get_inner_value().expose().as_bytes());
let signature = self.generate_signature(
auth,
host.to_string(),
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 01ce57d10e1..8004b3b5a12 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -1345,7 +1345,7 @@ pub fn construct_file_upload_request(
request.file_key,
request
.file_type
- .to_string()
+ .as_ref()
.split('/')
.last()
.unwrap_or_default()
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index af33ae21d76..a3335b2e228 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -77,10 +77,11 @@ where
| common_utils::request::Method::Put
| common_utils::request::Method::Delete
| common_utils::request::Method::Patch => {
- let body =
- types::RequestBody::get_inner_value(self.get_request_body(req, connectors)?)
- .peek()
- .to_owned();
+ let body = self
+ .get_request_body(req, connectors)?
+ .get_inner_value()
+ .peek()
+ .to_owned();
let md5_payload = crypto::Md5
.generate_digest(body.as_bytes())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index 2b9b45cdda6..e89810e79cf 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -241,11 +241,7 @@ where
.chars()
.skip(base_url.len() - 1)
.collect();
- let sha256 = self.generate_digest(
- types::RequestBody::get_inner_value(cybersource_req)
- .expose()
- .as_bytes(),
- );
+ let sha256 = self.generate_digest(cybersource_req.get_inner_value().expose().as_bytes());
let http_method = self.get_http_method();
let signature = self.generate_signature(
auth,
diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs
index 9fdb36ea1dc..b158f239fdd 100644
--- a/crates/router/src/connector/dlocal.rs
+++ b/crates/router/src/connector/dlocal.rs
@@ -68,9 +68,7 @@ where
"{}{}{}",
auth.x_login.peek(),
date,
- types::RequestBody::get_inner_value(dlocal_req)
- .peek()
- .to_owned()
+ dlocal_req.get_inner_value().peek().to_owned()
);
let authz = crypto::HmacSha256::sign_message(
&crypto::HmacSha256,
diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs
index 7db63f5eee5..fdd904ee737 100644
--- a/crates/router/src/connector/fiserv.rs
+++ b/crates/router/src/connector/fiserv.rs
@@ -78,7 +78,7 @@ where
.generate_authorization_signature(
auth,
&client_request_id,
- types::RequestBody::get_inner_value(fiserv_req).peek(),
+ fiserv_req.get_inner_value().peek(),
timestamp,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs
index 04f180efd08..d24a42085a4 100644
--- a/crates/router/src/connector/payeezy.rs
+++ b/crates/router/src/connector/payeezy.rs
@@ -44,8 +44,10 @@ where
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let auth = payeezy::PayeezyAuthType::try_from(&req.connector_auth_type)?;
- let request_payload =
- types::RequestBody::get_inner_value(self.get_request_body(req, connectors)?).expose();
+ let request_payload = self
+ .get_request_body(req, connectors)?
+ .get_inner_value()
+ .expose();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index b487740d07d..fd6de253047 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -222,7 +222,7 @@ impl
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let body = types::PaymentsAuthorizeType::get_request_body(self, req, connectors)?;
- let req_body = types::RequestBody::get_inner_value(body).expose();
+ let req_body = body.get_inner_value().expose();
let signature =
self.generate_signature(&auth, "post", "/v1/payments", &req_body, ×tamp, &salt)?;
let headers = vec![
@@ -555,7 +555,7 @@ impl
req.request.connector_transaction_id
);
let body = types::PaymentsCaptureType::get_request_body(self, req, connectors)?;
- let req_body = types::RequestBody::get_inner_value(body).expose();
+ let req_body = body.get_inner_value().expose();
let signature =
self.generate_signature(&auth, "post", &url_path, &req_body, ×tamp, &salt)?;
let headers = vec![
@@ -691,7 +691,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
let body = types::RefundExecuteType::get_request_body(self, req, connectors)?;
- let req_body = types::RequestBody::get_inner_value(body).expose();
+ let req_body = body.get_inner_value().expose();
let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
let signature =
self.generate_signature(&auth, "post", "/v1/refunds", &req_body, ×tamp, &salt)?;
diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs
index 72a9f6dbdbf..298f8fb1564 100644
--- a/crates/router/src/connector/riskified.rs
+++ b/crates/router/src/connector/riskified.rs
@@ -63,7 +63,7 @@ where
let riskified_req = self.get_request_body(req, connectors)?;
- let binding = types::RequestBody::get_inner_value(riskified_req);
+ let binding = riskified_req.get_inner_value();
let payload = binding.peek();
let digest = self
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index 2838edfbf91..6f022c9fca9 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -400,7 +400,7 @@ where
resp.merchant_id.clone(),
resp.payment_id.clone(),
resp.connector.clone(),
- resp.request.get_setup_mandate_details().map(Clone::clone),
+ resp.request.get_setup_mandate_details().cloned(),
maybe_customer,
pm_id.get_required_value("payment_method_id")?,
mandate_ids,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 26f6d6db193..dd109e99cb9 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -7,7 +7,6 @@ pub use api_models::enums::Connector;
use api_models::payments::CardToken;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
-pub use common_utils::request::RequestBody;
use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use diesel_models::enums;
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 67ad246ba7d..e0ab8131199 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -22,7 +22,7 @@ pub use api_models::{enums::Connector, mandates};
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
use common_enums::MandateStatus;
-pub use common_utils::request::{RequestBody, RequestContent};
+pub use common_utils::request::RequestContent;
use common_utils::{pii, pii::Email};
use data_models::mandates::{CustomerAcceptance, MandateData};
use error_stack::{IntoReport, ResultExt};
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 28b8f9ef796..1868eb9b4d9 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -3866,64 +3866,6 @@
]
}
},
- "/payouts/list": {
- "get": {
- "tags": [
- "Payouts"
- ],
- "summary": "Payouts - List",
- "description": "Payouts - List",
- "operationId": "List payouts",
- "responses": {
- "200": {
- "description": "Payouts listed",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PayoutListResponse"
- }
- }
- }
- },
- "404": {
- "description": "Payout not found"
- }
- },
- "security": [
- {
- "api_key": []
- }
- ]
- },
- "post": {
- "tags": [
- "Payouts"
- ],
- "summary": "Payouts - Filter",
- "description": "Payouts - Filter",
- "operationId": "Filter payouts",
- "responses": {
- "200": {
- "description": "Payouts filtered",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PayoutListResponse"
- }
- }
- }
- },
- "404": {
- "description": "Payout not found"
- }
- },
- "security": [
- {
- "api_key": []
- }
- ]
- }
- },
"/payouts/{payout_id}": {
"get": {
"tags": [
@@ -4116,6 +4058,64 @@
]
}
},
+ "/payouts/list": {
+ "get": {
+ "tags": [
+ "Payouts"
+ ],
+ "summary": "Payouts - List",
+ "description": "Payouts - List",
+ "operationId": "List payouts",
+ "responses": {
+ "200": {
+ "description": "Payouts listed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PayoutListResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payout not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ },
+ "post": {
+ "tags": [
+ "Payouts"
+ ],
+ "summary": "Payouts - Filter",
+ "description": "Payouts - Filter",
+ "operationId": "Filter payouts",
+ "responses": {
+ "200": {
+ "description": "Payouts filtered",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PayoutListResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payout not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/api_keys/{merchant_id)": {
"post": {
"tags": [
|
2024-03-21T18:15:20Z
|
## 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 the clippy lints occurring due to new rust version 1.77
### 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
|
14e1bbaf071d1178f91124fe85580f178cb1cf96
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4173
|
Bug: feat: get new filters for payments
Currently, /filter api for payments takes times to get list of all available filters, moreover it is dependent on time range. Need to extract all the available filters in less time, and these filters should not be dependent on time range.
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 10a68ef1a44..623abca8143 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -518,6 +518,12 @@ pub struct MerchantConnectorWebhookDetails {
pub additional_secret: Option<Secret<String>>,
}
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct MerchantConnectorInfo {
+ pub connector_label: String,
+ pub merchant_connector_id: String,
+}
+
/// Response of creating a new Merchant Connector for the merchant account."
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index b26ee0ae68e..b27ca142c94 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -9,8 +9,8 @@ use crate::{
},
payments::{
PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters,
- PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest,
- PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
+ PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest,
+ PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest,
PaymentsStartRequest, RedirectionResponse,
@@ -158,6 +158,11 @@ impl ApiEventMetric for PaymentListFilters {
Some(ApiEventsType::ResourceListAPI)
}
}
+impl ApiEventMetric for PaymentListFiltersV2 {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
impl ApiEventMetric for PaymentListConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 7e53e214075..a632933ea02 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1,4 +1,8 @@
-use std::{collections::HashMap, fmt, num::NonZeroI64};
+use std::{
+ collections::{HashMap, HashSet},
+ fmt,
+ num::NonZeroI64,
+};
use cards::CardNumber;
use common_utils::{
@@ -19,8 +23,11 @@ use url::Url;
use utoipa::ToSchema;
use crate::{
- admin, disputes, enums as api_enums, ephemeral_key::EphemeralKeyCreateResponse,
- mandates::RecurringDetails, refunds,
+ admin::{self, MerchantConnectorInfo},
+ disputes, enums as api_enums,
+ ephemeral_key::EphemeralKeyCreateResponse,
+ mandates::RecurringDetails,
+ refunds,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -3419,6 +3426,20 @@ pub struct PaymentListFilters {
pub authentication_type: Vec<enums::AuthenticationType>,
}
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PaymentListFiltersV2 {
+ /// The list of available connector filters
+ pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
+ /// The list of available currency filters
+ pub currency: Vec<enums::Currency>,
+ /// The list of available payment status filters
+ pub status: Vec<enums::IntentStatus>,
+ /// The list payment method and their corresponding types
+ pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
+ /// The list of available authentication types
+ pub authentication_type: Vec<enums::AuthenticationType>,
+}
+
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index ae8f49c759d..9dbe5f4f4bc 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1153,6 +1153,7 @@ pub enum MerchantStorageScheme {
serde::Deserialize,
serde::Serialize,
strum::Display,
+ strum::EnumIter,
strum::EnumString,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 4c087671a29..f0a30fbe662 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -11,8 +11,12 @@ pub mod tokenization;
pub mod transformers;
pub mod types;
+#[cfg(feature = "olap")]
+use std::collections::{HashMap, HashSet};
use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter};
+#[cfg(feature = "olap")]
+use api_models::admin::MerchantConnectorInfo;
use api_models::{
self, enums,
mandates::RecurringDetails,
@@ -33,6 +37,8 @@ use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use router_types::transformers::ForeignFrom;
use scheduler::utils as pt_utils;
+#[cfg(feature = "olap")]
+use strum::IntoEnumIterator;
use time;
pub use self::operations::{
@@ -2619,6 +2625,89 @@ pub async fn get_filters_for_payments(
))
}
+#[cfg(feature = "olap")]
+pub async fn get_payment_filters(
+ state: AppState,
+ merchant: domain::MerchantAccount,
+) -> RouterResponse<api::PaymentListFiltersV2> {
+ let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
+ super::admin::list_payment_connectors(state, merchant.merchant_id).await?
+ {
+ data
+ } else {
+ return Err(errors::ApiErrorResponse::InternalServerError.into());
+ };
+
+ let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new();
+ let mut payment_method_types_map: HashMap<
+ enums::PaymentMethod,
+ HashSet<enums::PaymentMethodType>,
+ > = HashMap::new();
+
+ // populate connector map
+ merchant_connector_accounts
+ .iter()
+ .filter_map(|merchant_connector_account| {
+ merchant_connector_account
+ .connector_label
+ .as_ref()
+ .map(|label| {
+ let info = MerchantConnectorInfo {
+ connector_label: label.clone(),
+ merchant_connector_id: merchant_connector_account
+ .merchant_connector_id
+ .clone(),
+ };
+ (merchant_connector_account.connector_name.clone(), info)
+ })
+ })
+ .for_each(|(connector_name, info)| {
+ connector_map
+ .entry(connector_name.clone())
+ .or_default()
+ .push(info);
+ });
+
+ // populate payment method type map
+ merchant_connector_accounts
+ .iter()
+ .flat_map(|merchant_connector_account| {
+ merchant_connector_account.payment_methods_enabled.as_ref()
+ })
+ .map(|payment_methods_enabled| {
+ payment_methods_enabled
+ .iter()
+ .filter_map(|payment_method_enabled| {
+ payment_method_enabled
+ .payment_method_types
+ .as_ref()
+ .map(|types_vec| (payment_method_enabled.payment_method, types_vec.clone()))
+ })
+ })
+ .for_each(|payment_methods_enabled| {
+ payment_methods_enabled.for_each(|(payment_method, payment_method_types_vec)| {
+ payment_method_types_map
+ .entry(payment_method)
+ .or_default()
+ .extend(
+ payment_method_types_vec
+ .iter()
+ .map(|p| p.payment_method_type),
+ );
+ });
+ });
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListFiltersV2 {
+ connector: connector_map,
+ currency: enums::Currency::iter().collect(),
+ status: enums::IntentStatus::iter().collect(),
+ payment_method: payment_method_types_map,
+ authentication_type: enums::AuthenticationType::iter().collect(),
+ },
+ ))
+}
+
pub async fn add_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 74bb8bbc242..3bc68ff79b5 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -318,6 +318,7 @@ impl Payments {
.route(web::post().to(payments_list_by_filter)),
)
.service(web::resource("/filter").route(web::post().to(get_filters_for_payments)))
+ .service(web::resource("/filter_v2").route(web::get().to(get_payment_filters)))
}
#[cfg(feature = "oltp")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 56df8b171c4..d9887ac0342 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -114,6 +114,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsSessionToken
| Flow::PaymentsStart
| Flow::PaymentsList
+ | Flow::PaymentsFilters
| Flow::PaymentsRedirect
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExternalAuthentication
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index ac45228f90d..c3331817784 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -959,6 +959,29 @@ pub async fn get_filters_for_payments(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
+#[cfg(feature = "olap")]
+pub async fn get_payment_filters(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+) -> impl Responder {
+ let flow = Flow::PaymentsFilters;
+ api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth, _, _| payments::get_payment_filters(state, auth.merchant_account),
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::PaymentRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ )
+ .await
+}
+
#[cfg(feature = "oltp")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsApprove, payment_id))]
// #[post("/{payment_id}/approve")]
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 370e0ca3509..4fc3fb44521 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -3,10 +3,10 @@ pub use api_models::payments::{
CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData,
MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate,
PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints,
- PaymentListFilters, PaymentListResponse, PaymentListResponseV2, PaymentMethodData,
- PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody,
- PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, PaymentsCancelRequest,
- PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
+ PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2,
+ PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp,
+ PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest,
+ PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
PaymentsIncrementalAuthorizationRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse,
PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm,
PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 06667f96bb3..240bf379f6c 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -151,6 +151,8 @@ pub enum Flow {
PaymentsStart,
/// Payments list flow.
PaymentsList,
+ // Payments filters flow
+ PaymentsFilters,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
|
2024-03-21T20:00:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The api is used to get all the available filters that can be applied on payments list. This is filter_v2 api that performs better than the previous payments api and it is not dependent on any time range value. Filters will remain static and won't change as per time range. Though this new api seems static but it will fetch dynamic values in some cases. For example it will only show list of configured connectors, payment methods and types instead of everything. Thus limiting the size of list and only showing configured ones.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#4173](https://github.com/juspay/hyperswitch/issues/4173)
## How did you test it?
Request:
```
curl --location 'http://localhost:8080/payments/filter_v2' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response will be something like:
```
{
"connector": {
"stripe_test": [
{
"connector_label": "stripe_test_default",
"merchant_connector_id": "mca_B5FTmcB8Ff8pzQjgzpyF"
}
],
"paypal": [
{
"connector_label": "ksldjflksdfj",
"merchant_connector_id": "mca_LpoFnsWU74B7Fndy09jI"
},
{
"connector_label": "paypal_default",
"merchant_connector_id": "mca_NSQClE2JbgVkw4arbJBl"
},
{
"connector_label": "xyz",
"merchant_connector_id": "mca_XxrVLrHJ2ORoSRurw8Wz"
}
]
},
"currency": [
"AED",
"ALL",
"AMD",
"ANG",
"AOA",
"ARS",
"AUD",
"AWG",
"AZN",
"BAM",
"BBD",
"BDT",
"BGN",
"BHD",
"BIF",
"BMD",
"BND",
"BOB",
"BRL",
"BSD",
"BWP",
"BYN",
"BZD",
"CAD",
"CHF",
"CLP",
"CNY",
"COP",
"CRC",
"CUP",
"CVE",
"CZK",
"DJF",
"DKK",
"DOP",
"DZD",
"EGP",
"ETB",
"EUR",
"FJD",
"FKP",
"GBP",
"GEL",
"GHS",
"GIP",
"GMD",
"GNF",
"GTQ",
"GYD",
"HKD",
"HNL",
"HRK",
"HTG",
"HUF",
"IDR",
"ILS",
"INR",
"IQD",
"JMD",
"JOD",
"JPY",
"KES",
"KGS",
"KHR",
"KMF",
"KRW",
"KWD",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"LYD",
"MAD",
"MDL",
"MGA",
"MKD",
"MMK",
"MNT",
"MOP",
"MRU",
"MUR",
"MVR",
"MWK",
"MXN",
"MYR",
"MZN",
"NAD",
"NGN",
"NIO",
"NOK",
"NPR",
"NZD",
"OMR",
"PAB",
"PEN",
"PGK",
"PHP",
"PKR",
"PLN",
"PYG",
"QAR",
"RON",
"RSD",
"RUB",
"RWF",
"SAR",
"SBD",
"SCR",
"SEK",
"SGD",
"SHP",
"SLE",
"SLL",
"SOS",
"SRD",
"SSP",
"STN",
"SVC",
"SZL",
"THB",
"TND",
"TOP",
"TRY",
"TTD",
"TWD",
"TZS",
"UAH",
"UGX",
"USD",
"UYU",
"UZS",
"VES",
"VND",
"VUV",
"WST",
"XAF",
"XCD",
"XOF",
"XPF",
"YER",
"ZAR",
"ZMW"
],
"status": [
"succeeded",
"failed",
"cancelled",
"processing",
"requires_customer_action",
"requires_merchant_action",
"requires_payment_method",
"requires_confirmation",
"requires_capture",
"partially_captured",
"partially_captured_and_capturable"
],
"payment_method": {
"card": [
"credit",
"debit"
],
"pay_later": [
"afterpay_clearpay",
"klarna",
"affirm"
]
},
"authentication_type": [
"three_ds",
"no_three_ds"
]
}
```
It will depend on connector and payment methods configurations.
## Checklist
<!-- Put an `x` in 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
|
1b7cde2d1b687e9c5ca8e3c02eef5c7d3fb7da8f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4157
|
Bug: [CI] update hotfix pr check workflow to parse backticks in pr title
Currently backticks in hotfix pr title is not being parsed resulting in hotfix-pr-check workflow failing. Update the workflow to parse backticks too
|
2024-03-20T17:46:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently backticks in hotfix pr title is not being parsed resulting in hotfix-pr-check workflow failing. This PR updates the workflow to store pr title in env and make use of it.
Failing CI check (example) - https://github.com/juspay/hyperswitch/actions/runs/8359058549/job/22884641822
This PR also updates conventional check workflow to store commit message in env
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
7c0e4c7229acacbeb93102bcdc25b74fd7a3314c
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4151
|
Bug: HOTIFIX - [FIX] update payment method status only if existing status is not active
Currently we update the payment method status if the existing status doesn't match the attempt status. Update the status only if the existing status is not active.
|
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 447ca14b156..77b72f0fd57 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -904,7 +904,9 @@ async fn update_payment_method_status<F: Clone>(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- if pm.status != attempt_status.into() {
+ if pm.status != common_enums::PaymentMethodStatus::Active
+ && pm.status != attempt_status.into()
+ {
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
payment_data.payment_method_status = Some(updated_pm_status);
|
2024-03-20T10:14:01Z
|
## 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 -->
Original PR - https://github.com/juspay/hyperswitch/pull/4149
### 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
|
f9db641058179b846d4bf3ce69a7679b4e9541fc
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4153
|
Bug: make `ApplepayPaymentMethod` in payment_method_data column of `payment_attempt` table as json
make `ApplepayPaymentMethod` in payment_method_data column of `payment_attempt` table as json because retrieve payment fails for the old payments for which the `payment_method_data` in the `payment_attempt` table was stored as `{"wallet": {}}`. But after this change there would be some data for the apple pay (`{"wallet": {"apple_pay": {"type": "debit", "network": "Visa", "display_name": "Visa 1234"}}}`) or `{"wallet": null}`
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 40d11543c02..d96616fcaaa 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1480,12 +1480,6 @@ pub struct AdditionalCardInfo {
pub authentication_data: Option<serde_json::Value>,
}
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum Wallets {
- ApplePay(ApplepayPaymentMethod),
-}
-
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AdditionalPaymentData {
@@ -1493,7 +1487,9 @@ pub enum AdditionalPaymentData {
BankRedirect {
bank_name: Option<api_enums::BankNames>,
},
- Wallet(Option<Wallets>),
+ Wallet {
+ apple_pay: Option<ApplepayPaymentMethod>,
+ },
PayLater {},
BankTransfer {},
Crypto {},
@@ -2084,7 +2080,7 @@ where
| PaymentMethodDataResponse::PayLater {}
| PaymentMethodDataResponse::Paypal {}
| PaymentMethodDataResponse::Upi {}
- | PaymentMethodDataResponse::Wallet(_)
+ | PaymentMethodDataResponse::Wallet {}
| PaymentMethodDataResponse::BankTransfer {}
| PaymentMethodDataResponse::Voucher {} => {
payment_method_data_response.serialize(serializer)
@@ -2101,7 +2097,7 @@ pub enum PaymentMethodDataResponse {
#[serde(rename = "card")]
Card(Box<CardResponse>),
BankTransfer {},
- Wallet(Option<Wallets>),
+ Wallet {},
PayLater {},
Paypal {},
BankRedirect {},
@@ -3040,7 +3036,7 @@ impl From<AdditionalPaymentData> for PaymentMethodDataResponse {
match payment_method_data {
AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))),
AdditionalPaymentData::PayLater {} => Self::PayLater {},
- AdditionalPaymentData::Wallet(wallet) => Self::Wallet(wallet),
+ AdditionalPaymentData::Wallet { .. } => Self::Wallet {},
AdditionalPaymentData::BankRedirect { .. } => Self::BankRedirect {},
AdditionalPaymentData::Crypto {} => Self::Crypto {},
AdditionalPaymentData::BankDebit {} => Self::BankDebit {},
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 7493c787f4e..112e3e64d6d 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3527,13 +3527,11 @@ pub async fn get_additional_payment_data(
}
api_models::payments::PaymentMethodData::Wallet(wallet) => match wallet {
api_models::payments::WalletData::ApplePay(apple_pay_wallet_data) => {
- api_models::payments::AdditionalPaymentData::Wallet(Some(
- api_models::payments::Wallets::ApplePay(
- apple_pay_wallet_data.payment_method.to_owned(),
- ),
- ))
+ api_models::payments::AdditionalPaymentData::Wallet {
+ apple_pay: Some(apple_pay_wallet_data.payment_method.to_owned()),
+ }
}
- _ => api_models::payments::AdditionalPaymentData::Wallet(None),
+ _ => api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None },
},
api_models::payments::PaymentMethodData::PayLater(_) => {
api_models::payments::AdditionalPaymentData::PayLater {}
|
2024-03-20T10:54:27Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
make ApplepayPaymentMethod in payment_method_data column of payment_attempt table as json because retrieve payment fails for the old payments for which the payment_method_data in the payment_attempt table was stored as {"wallet": {}}
### 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 #4153.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Checkout to old commit where we were storing the `{"wallet": {}}` for apple pay in the `payment_attempt` table
<img width="1450" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/15cbd523-f2cb-4275-8d61-897ae958d8c5">
Make a payment create call for apple pay
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"payment_data",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}
```
Checkout to the latest main and retrieve the payment with the `payment_id`
```
curl --location 'http://localhost:8080/payments/pay_rhuPyFWzD4SM0spkpjXi' \
--header 'Accept: application/json' \
--header 'api-key: dev_jhuZ9QNa1RSObflo1fGgAc7ZsZDGLQ20XKErfgB3uXyfOZEtAWM73JI8QbD2t9j0' \
--data ''
```
<img width="1425" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0d7bfa20-b980-4376-a0f3-10cd8671ba0a">
<img width="1534" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/29b13f8d-36f2-454a-af82-51e95bb5492c">
## Checklist
<!-- Put an `x` in 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
|
3653c2c108b80a20df6e8a2bf980d48c204376cd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4163
|
Bug: feat: create an api to get countries and currencies for a connector and pmt
Currently there is no way to set countries and currencies for a particular connector and payment method type. This api should give the list of countries and currencies supported by a given connector and payment method type combination. This will be used by frontend to set filters.
|
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 346ee34b2cf..b26ee0ae68e 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -3,8 +3,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::{
payment_methods::{
CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse,
- DefaultPaymentMethod, PaymentMethodDeleteResponse, PaymentMethodListRequest,
- PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate,
+ DefaultPaymentMethod, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
+ PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse,
+ PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters,
@@ -131,6 +132,9 @@ impl ApiEventMetric for PaymentMethodListRequest {
}
}
+impl ApiEventMetric for ListCountriesCurrenciesRequest {}
+
+impl ApiEventMetric for ListCountriesCurrenciesResponse {}
impl ApiEventMetric for PaymentMethodListResponse {}
impl ApiEventMetric for CustomerDefaultPaymentMethodResponse {
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 37580edbc71..f08a793ebf5 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use cards::CardNumber;
use common_utils::{
@@ -914,6 +914,26 @@ pub struct TokenizedCardValue1 {
pub card_token: Option<String>,
}
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListCountriesCurrenciesRequest {
+ pub connector: api_enums::Connector,
+ pub payment_method_type: api_enums::PaymentMethodType,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListCountriesCurrenciesResponse {
+ pub currencies: HashSet<api_enums::Currency>,
+ pub countries: HashSet<CountryCodeWithName>,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq)]
+pub struct CountryCodeWithName {
+ pub code: api_enums::CountryAlpha2,
+ pub name: api_enums::Country,
+}
+
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue2 {
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a1156366d33..2ba3551c1e3 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1581,6 +1581,7 @@ pub enum DisputeStatus {
serde::Deserialize,
serde::Serialize,
strum::Display,
+ strum::EnumIter,
strum::EnumString,
utoipa::ToSchema,
Copy
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 289654f93ed..2a6c29ce803 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -7,8 +7,9 @@ use api_models::{
admin::{self, PaymentMethodsEnabled},
enums::{self as api_enums},
payment_methods::{
- BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes,
- CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes,
+ BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName,
+ CustomerDefaultPaymentMethodResponse, ListCountriesCurrenciesRequest,
+ ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes,
PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
ResponsePaymentMethodsEnabled,
@@ -30,6 +31,7 @@ use domain::CustomerUpdate;
use error_stack::{report, IntoReport, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
+use strum::IntoEnumIterator;
use super::surcharge_decision_configs::{
perform_surcharge_decision_management_for_payment_method_list,
@@ -3606,3 +3608,59 @@ pub async fn create_encrypted_payment_method_data(
pm_data_encrypted
}
+
+pub async fn list_countries_currencies_for_connector_payment_method(
+ state: routes::AppState,
+ req: ListCountriesCurrenciesRequest,
+) -> errors::RouterResponse<ListCountriesCurrenciesResponse> {
+ Ok(services::ApplicationResponse::Json(
+ list_countries_currencies_for_connector_payment_method_util(
+ state.conf.pm_filters.clone(),
+ req.connector,
+ req.payment_method_type,
+ )
+ .await,
+ ))
+}
+
+// This feature will be more efficient as a WASM function rather than as an API.
+// So extracting this logic to a separate function so that it can be used in WASM as well.
+pub async fn list_countries_currencies_for_connector_payment_method_util(
+ connector_filters: settings::ConnectorFilters,
+ connector: api_enums::Connector,
+ payment_method_type: api_enums::PaymentMethodType,
+) -> ListCountriesCurrenciesResponse {
+ let payment_method_type =
+ settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type);
+
+ let (currencies, country_codes) = connector_filters
+ .0
+ .get(&connector.to_string())
+ .and_then(|filter| filter.0.get(&payment_method_type))
+ .map(|filter| (filter.currency.clone(), filter.country.clone()))
+ .unwrap_or_else(|| {
+ connector_filters
+ .0
+ .get("default")
+ .and_then(|filter| filter.0.get(&payment_method_type))
+ .map_or((None, None), |filter| {
+ (filter.currency.clone(), filter.country.clone())
+ })
+ });
+
+ let currencies =
+ currencies.unwrap_or_else(|| api_enums::Currency::iter().collect::<HashSet<_>>());
+ let country_codes =
+ country_codes.unwrap_or_else(|| api_enums::CountryAlpha2::iter().collect::<HashSet<_>>());
+
+ ListCountriesCurrenciesResponse {
+ currencies,
+ countries: country_codes
+ .into_iter()
+ .map(|country_code| CountryCodeWithName {
+ code: country_code,
+ name: common_enums::Country::from_alpha2(country_code),
+ })
+ .collect(),
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 7d6b6c8ad28..f67b82faf3f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -19,8 +19,6 @@ use tokio::sync::oneshot;
#[cfg(feature = "olap")]
use super::blocklist;
-#[cfg(any(feature = "olap", feature = "oltp"))]
-use super::currency;
#[cfg(feature = "dummy_connector")]
use super::dummy_connector::*;
#[cfg(feature = "payouts")]
@@ -39,8 +37,10 @@ use super::{
use super::{cache::*, health::*};
#[cfg(any(feature = "olap", feature = "oltp"))]
use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*};
+#[cfg(any(feature = "olap", feature = "oltp"))]
+use super::{currency, payment_methods::*};
#[cfg(feature = "oltp")]
-use super::{ephemeral_key::*, payment_methods::*, webhooks::*};
+use super::{ephemeral_key::*, webhooks::*};
use crate::configs::secrets_transformers;
#[cfg(all(feature = "frm", feature = "oltp"))]
use crate::routes::fraud_check as frm_routes;
@@ -738,24 +738,39 @@ impl Payouts {
pub struct PaymentMethods;
-#[cfg(feature = "oltp")]
+#[cfg(any(feature = "olap", feature = "oltp"))]
impl PaymentMethods {
pub fn server(state: AppState) -> Scope {
- web::scope("/payment_methods")
- .app_data(web::Data::new(state))
- .service(
- web::resource("")
- .route(web::post().to(create_payment_method_api))
- .route(web::get().to(list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later
- )
- .service(
- web::resource("/{payment_method_id}")
- .route(web::get().to(payment_method_retrieve_api))
- .route(web::post().to(payment_method_update_api))
- .route(web::delete().to(payment_method_delete_api)),
- )
- .service(web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)))
- .service(web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token)))
+ let mut route = web::scope("/payment_methods").app_data(web::Data::new(state));
+ #[cfg(feature = "olap")]
+ {
+ route = route.service(
+ web::resource("/filter")
+ .route(web::get().to(list_countries_currencies_for_connector_payment_method)),
+ );
+ }
+ #[cfg(feature = "oltp")]
+ {
+ route = route
+ .service(
+ web::resource("")
+ .route(web::post().to(create_payment_method_api))
+ .route(web::get().to(list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later
+ )
+ .service(
+ web::resource("/{payment_method_id}")
+ .route(web::get().to(payment_method_retrieve_api))
+ .route(web::post().to(payment_method_update_api))
+ .route(web::delete().to(payment_method_delete_api)),
+ )
+ .service(
+ web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)),
+ )
+ .service(
+ web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token)),
+ )
+ }
+ route
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 43802d24451..fd7bdb9019e 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -97,6 +97,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodsUpdate
| Flow::PaymentMethodsDelete
| Flow::ValidatePaymentMethod
+ | Flow::ListCountriesCurrencies
| Flow::DefaultPaymentMethodsSet => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 1e2e66d583c..7ef20994e2e 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -8,7 +8,7 @@ use time::PrimitiveDateTime;
use super::app::AppState;
use crate::{
core::{api_locking, errors, payment_methods::cards},
- services::{api, authentication as auth},
+ services::{api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
storage::payment_method::PaymentTokenData,
@@ -262,6 +262,35 @@ pub async fn payment_method_delete_api(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
+pub async fn list_countries_currencies_for_connector_payment_method(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
+) -> HttpResponse {
+ let flow = Flow::ListCountriesCurrencies;
+ let payload = query_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _auth: auth::AuthenticationData, req| {
+ cards::list_countries_currencies_for_connector_payment_method(state, req)
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
pub async fn default_payment_method_set_api(
state: web::Data<AppState>,
@@ -297,7 +326,6 @@ pub async fn default_payment_method_set_api(
))
.await
}
-
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 642e94ad69e..13c9ec61f2a 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -1,11 +1,11 @@
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
- GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate,
- PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest,
- PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
- TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
- TokenizedWalletValue1, TokenizedWalletValue2,
+ GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
+ PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList,
+ PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
+ PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
+ TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
};
use error_stack::report;
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b521acbdcdc..635c6268d67 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -117,6 +117,8 @@ pub enum Flow {
CustomerPaymentMethodsList,
/// List Customers for a merchant
CustomersList,
+ /// Retrieve countries and currencies for connector and payment method
+ ListCountriesCurrencies,
/// Payment methods retrieve flow.
PaymentMethodsRetrieve,
/// Payment methods update flow.
|
2024-03-19T09:33:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Make a api to fetch the countries and currencies supported by a particular connector.
This api will be used by the dashboard to restrict payment methods to specific countries/currencies.
### 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 #4163
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- When the filters are set for the combination of connector and payment method type
```
curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=affirm' \
--header 'Authorization: Bearer JWT' \
```
```
{
"currencies": [
"USD"
],
"countries": [
{
"code": "US",
"name": "UnitedStatesOfAmerica"
}
]
}
```
- When the filters are not set for the given combination, we will use default filters to get the list
```
curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=paypal' \
--header 'Authorization: Bearer JWT' \
```
```
{
"currencies": [
"BRL",
"INR",
"EUR",
"JPY",
"CHF",
"USD",
"PLN",
"MYR",
"PHP",
"SGD",
"THB",
"SEK",
"RUB",
"CAD",
"HKD",
"CZK",
"NOK",
"NZD",
"HUF",
"GBP",
"AUD",
"DKK",
"MXN"
],
"countries": [
{
"code": "DE",
"name": "Germany"
},
...
{
"code": "ZA",
"name": "SouthAfrica"
}
]
}
```
- If the filters are not set in default also, then the list of all countries and currencies will be sent
- When the filters are not set for the given combination, we will use default filters to get the list
```
curl --location 'http://localhost:8080/payment_methods/filter?connector=stripe&paymentMethodType=paypal' \
--header 'Authorization: Bearer JWT' \
```
```
{
"currencies": [
"XPF",
...
"ZMW"
],
"countries": [
{
"code": "DE",
"name": "Germany"
},
...
{
"code": "ZA",
"name": "SouthAfrica"
}
]
}
```
## Checklist
<!-- Put 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
|
b8c927593a85792588e582bf25f2daadfa5f7fb0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4148
|
Bug: [FIX] update payment method status only if existing status is not active
Currently we update the payment method status if the existing status doesn't match the attempt status. Update the status only if the existing status is not active.
|
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index ae350d6de2b..0167f16cb8a 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -936,7 +936,9 @@ async fn update_payment_method_status<F: Clone>(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- if pm.status != attempt_status.into() {
+ if pm.status != common_enums::PaymentMethodStatus::Active
+ && pm.status != attempt_status.into()
+ {
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
payment_data
|
2024-03-20T09:54:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently we update the payment method status if the existing status doesn't match the attempt status. Update the status only if the existing status is not active.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Create Stripe mca
2. Create normal payment and save the card (payment fails as below used is a failure test card)
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "customer1",
"business_country": "US",
"business_label": "default",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "10",
"card_exp_year": "50",
"card_holder_name": "John",
"card_cvc": "737"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}'
```
3. Create another payment with confirm = false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "customer1",
"business_country": "US",
"business_label": "default",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}'
```
3. Do list customer payment methods and make sure the above added payment method is listed. Take the payment token and confirm the payment
```
curl --location 'http://localhost:8080/payments/pay_BxKOv6lt4b00dYXgT2Mj/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_token": "token_soc9EzErpjamqPmPEMbm"
}'
```
This goes to failure.
4. List customer payment methods and the above added payment method should still be listed
## Checklist
<!-- Put an `x` in 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
|
3653c2c108b80a20df6e8a2bf980d48c204376cd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4137
|
Bug: Fails to build with rust 1.77.0
### Bug Description
I have the following error with rust 1.77.0:
```
--- stderr
thread 'main' panicked at crates/router_env/src/cargo_workspace.rs:57:5:
Unknown workspace members package ID format. Please run `cargo metadata --format-version=1 | jq '.workspace_members'` and update this build script to match the updated package ID format.
```
The format of ids in 'cargo metadata' has changed with cargo 1.77, it's documented here: https://github.com/rust-lang/cargo/issues/13528
### Expected Behavior
It should build.
### Actual Behavior
It fails to build.
### Steps To Reproduce
exec `cargo build` with rust 1.77.0
### Context For The Bug
```
--- stderr
thread 'main' panicked at crates/router_env/src/cargo_workspace.rs:57:5:
Unknown workspace members package ID format. Please run `cargo metadata --format-version=1 | jq '.workspace_members'` and update this build script to match the updated package ID format.
```
### Environment
If not (or if building/running locally), please provide the following details:
1. Operating System: FreeBSD
2. Rust version (output of `rustc --version`): ```rustc 1.77.0 (aedd173a2 2024-03-17) (built from a source tarball)
binary: rustc
commit-hash: aedd173a2c086e558c2b66d3743b344f977621a7
commit-date: 2024-03-17
host: x86_64-unknown-freebsd
release: 1.77.0
LLVM version: 17.0.6```
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/Cargo.lock b/Cargo.lock
index 03f78686981..33327b71589 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1764,9 +1764,9 @@ dependencies = [
[[package]]
name = "cargo_metadata"
-version = "0.15.4"
+version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a"
+checksum = "2d886547e41f740c616ae73108f6eb70afe6d940c7bc697cb30f13daec073037"
dependencies = [
"camino",
"cargo-platform",
@@ -5690,7 +5690,7 @@ dependencies = [
name = "router_env"
version = "0.1.0"
dependencies = [
- "cargo_metadata 0.15.4",
+ "cargo_metadata 0.18.1",
"config",
"error-stack",
"gethostname",
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 3a4dcf128be..a028dfb8e56 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -8,7 +8,7 @@ readme = "README.md"
license.workspace = true
[dependencies]
-cargo_metadata = "0.15.4"
+cargo_metadata = "0.18.1"
config = { version = "0.13.3", features = ["toml"] }
error-stack = "0.3.1"
gethostname = "0.4.3"
@@ -34,7 +34,7 @@ vergen = { version = "8.2.1", optional = true, features = ["cargo", "git", "git2
tokio = { version = "1.36.0", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
-cargo_metadata = "0.15.4"
+cargo_metadata = "0.18.1"
vergen = { version = "8.2.1", features = ["cargo", "git", "git2", "rustc"], optional = true }
[features]
diff --git a/crates/router_env/src/cargo_workspace.rs b/crates/router_env/src/cargo_workspace.rs
index 3fd92fc57c4..fd4ce38712a 100644
--- a/crates/router_env/src/cargo_workspace.rs
+++ b/crates/router_env/src/cargo_workspace.rs
@@ -14,17 +14,11 @@ pub fn set_cargo_workspace_members_env() {
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.expect("Failed to obtain cargo metadata");
- let workspace_members = metadata.workspace_members;
- let workspace_members = workspace_members
+ let workspace_members = metadata
+ .workspace_packages()
.iter()
- .map(|package_id| {
- package_id
- .repr
- .split_once(' ')
- .expect("Unknown cargo metadata package ID format")
- .0
- })
+ .map(|package| package.name.as_str())
.collect::<Vec<_>>()
.join(",");
@@ -35,7 +29,7 @@ pub fn set_cargo_workspace_members_env() {
.expect("Failed to set `CARGO_WORKSPACE_MEMBERS` environment variable");
}
-/// Verify that the cargo metadata workspace members format matches that expected by
+/// Verify that the cargo metadata workspace packages format matches that expected by
/// [`set_cargo_workspace_members_env`] to set the `CARGO_WORKSPACE_MEMBERS` environment variable.
///
/// This function should be typically called within build scripts, before the
@@ -43,24 +37,20 @@ pub fn set_cargo_workspace_members_env() {
///
/// # Panics
///
-/// Panics if running the `cargo metadata` command fails, or if the workspace members package ID
-/// format cannot be determined.
+/// Panics if running the `cargo metadata` command fails, or if the workspace member package names
+/// cannot be determined.
pub fn verify_cargo_metadata_format() {
#[allow(clippy::expect_used)]
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.expect("Failed to obtain cargo metadata");
- let workspace_members = metadata.workspace_members;
- let package_id_entry_prefix =
- format!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
assert!(
- workspace_members
+ metadata
+ .workspace_packages()
.iter()
- .any(|package_id| package_id.repr.starts_with(&package_id_entry_prefix)),
- "Unknown workspace members package ID format. \
- Please run `cargo metadata --format-version=1 | jq '.workspace_members'` and update this \
- build script to match the updated package ID format."
+ .any(|package| package.name == env!("CARGO_PKG_NAME")),
+ "Unable to determine workspace member package names from `cargo metadata`"
);
}
|
2024-03-19T19:57:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [x] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR updates the build script code to obtain cargo workspace member package names to use a better and more deterministic way to do so.
Previously, we used to perform string manipulation on the package ID format (obtained from the `workspace_members` field in `cargo metadata --format-version=1`), and the package ID format was not stabilized (until recently). The package ID format has been [stabilized](https://github.com/rust-lang/cargo/pull/12914) in Rust 1.77, and the stabilized format breaks our existing build scripts. This PR updates the build script code to instead obtain the workspace member package names using the [`Metadata::workspace_packages()`](https://docs.rs/cargo_metadata/0.18.1/cargo_metadata/struct.Metadata.html#method.workspace_packages) method that the `cargo_metadata` crate provides.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This would fix builds from breaking once Rust 1.77 is released as the stable version on March 21st, 2024.
Fixes #4137.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
`cargo run` was successful with both Rust 1.76 and 1.77 (although with warnings).
I installed the Rust 1.77 toolchain by following the instructions from the [Rust 1.77.0 pre-release testing](https://blog.rust-lang.org/inside-rust/2024/03/17/1.77.0-prerelease.html) blog post.
## Checklist
<!-- Put an `x` in 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
|
f3141ecbf9cbf5149ab2d17e1e9068ec9f40ef4a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4170
|
Bug: [REFACTOR]: Create a domain function for saving payment method and updating pm_id in attempt
<img width="1404" alt="Screenshot 2024-03-21 at 22 08 28" src="https://github.com/juspay/hyperswitch/assets/61520228/c6cdfd23-096a-402b-8449-b7afdd2614de">
|
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index ec0e0873168..0c165632047 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -338,6 +338,10 @@ pub enum PaymentAttemptUpdate {
error_message: Option<Option<String>>,
updated_by: String,
},
+ PaymentMethodDetailsUpdate {
+ payment_method_id: Option<String>,
+ updated_by: String,
+ },
VoidUpdate {
status: storage_enums::AttemptStatus,
cancellation_reason: Option<String>,
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 6ad21eab12b..603e0f4ebf2 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -237,6 +237,10 @@ pub enum PaymentAttemptUpdate {
cancellation_reason: Option<String>,
updated_by: String,
},
+ PaymentMethodDetailsUpdate {
+ payment_method_id: Option<String>,
+ updated_by: String,
+ },
BlocklistUpdate {
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
@@ -644,6 +648,14 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
merchant_connector_id: Some(None),
..Default::default()
},
+ PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
+ payment_method_id,
+ updated_by,
+ } => Self {
+ payment_method_id,
+ updated_by,
+ ..Default::default()
+ },
PaymentAttemptUpdate::ResponseUpdate {
status,
connector,
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index b54091e4923..84aa9b48e6f 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -340,156 +340,134 @@ where
.change_context(errors::ApiErrorResponse::MandateUpdateFailed)?;
Ok(resp)
}
+
pub async fn mandate_procedure<F, FData>(
state: &AppState,
- mut resp: types::RouterData<F, FData, types::PaymentsResponseData>,
- maybe_customer: &Option<domain::Customer>,
+ resp: &types::RouterData<F, FData, types::PaymentsResponseData>,
+ customer_id: &Option<String>,
pm_id: Option<String>,
merchant_connector_id: Option<String>,
storage_scheme: MerchantStorageScheme,
-) -> errors::RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
+) -> errors::RouterResult<Option<String>>
where
FData: MandateBehaviour,
{
- match resp.response {
- Err(_) => {}
- Ok(_) => match resp.request.get_mandate_id() {
- Some(mandate_id) => {
- if let Some(ref mandate_id) = mandate_id.mandate_id {
- let orig_mandate = state
- .store
- .find_mandate_by_merchant_id_mandate_id(
- resp.merchant_id.as_ref(),
- mandate_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
- let mandate = match orig_mandate.mandate_type {
- storage_enums::MandateType::SingleUse => state
- .store
- .update_mandate_by_merchant_id_mandate_id(
- &resp.merchant_id,
- mandate_id,
- storage::MandateUpdate::StatusUpdate {
- mandate_status: storage_enums::MandateStatus::Revoked,
- },
- orig_mandate,
- storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
- storage_enums::MandateType::MultiUse => state
- .store
- .update_mandate_by_merchant_id_mandate_id(
- &resp.merchant_id,
- mandate_id,
- storage::MandateUpdate::CaptureAmountUpdate {
- amount_captured: Some(
- orig_mandate.amount_captured.unwrap_or(0)
- + resp.request.get_amount(),
- ),
- },
- orig_mandate,
- storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
- }?;
- metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
- &metrics::CONTEXT,
- 1,
- &[metrics::request::add_attributes(
- "connector",
- mandate.connector,
- )],
- );
- resp.payment_method_id = Some(mandate.payment_method_id);
- }
- }
- None => {
- if resp.request.get_setup_mandate_details().is_some() {
- resp.payment_method_id = pm_id.clone();
- let (mandate_reference, network_txn_id) = match resp.response.as_ref().ok() {
- Some(types::PaymentsResponseData::TransactionResponse {
- mandate_reference,
- network_txn_id,
- ..
- }) => (mandate_reference.clone(), network_txn_id.clone()),
- _ => (None, None),
- };
-
- let mandate_ids = mandate_reference
- .as_ref()
- .map(|md| {
- md.encode_to_value()
- .change_context(
- errors::ApiErrorResponse::MandateSerializationFailed,
- )
- .map(masking::Secret::new)
- })
- .transpose()?;
-
- if let Some(new_mandate_data) = payment_helper::generate_mandate(
- resp.merchant_id.clone(),
- resp.payment_id.clone(),
- resp.connector.clone(),
- resp.request.get_setup_mandate_details().cloned(),
- maybe_customer,
- pm_id.get_required_value("payment_method_id")?,
- mandate_ids,
- network_txn_id,
- get_insensitive_payment_method_data_if_exists(&resp),
- mandate_reference,
- merchant_connector_id,
- )? {
- let connector = new_mandate_data.connector.clone();
- logger::debug!("{:?}", new_mandate_data);
- resp.request
- .set_mandate_id(Some(api_models::payments::MandateIds {
- mandate_id: Some(new_mandate_data.mandate_id.clone()),
- mandate_reference_id: new_mandate_data
- .connector_mandate_ids
- .clone()
- .map(|ids| {
- Some(ids)
- .parse_value::<api_models::payments::ConnectorMandateReferenceId>(
- "ConnectorMandateId",
- )
- .change_context(errors::ApiErrorResponse::MandateDeserializationFailed)
- })
- .transpose()?
- .map_or(
- new_mandate_data.network_transaction_id.clone().map(|id| {
- api_models::payments::MandateReferenceId::NetworkMandateId(
- id,
- )
- }),
- |connector_id| Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
- api_models::payments::ConnectorMandateReferenceId {
- connector_mandate_id: connector_id.connector_mandate_id,
- payment_method_id: connector_id.payment_method_id,
- update_history:None,
-
- }
- )))
- }));
- state
- .store
- .insert_mandate(new_mandate_data, storage_scheme)
- .await
- .to_duplicate_response(errors::ApiErrorResponse::DuplicateMandate)?;
- metrics::MANDATE_COUNT.add(
- &metrics::CONTEXT,
- 1,
- &[metrics::request::add_attributes("connector", connector)],
- );
- };
- }
- }
- },
+ let Ok(ref response) = resp.response else {
+ return Ok(None);
+ };
+
+ match resp.request.get_mandate_id() {
+ Some(mandate_id) => {
+ let Some(ref mandate_id) = mandate_id.mandate_id else {
+ return Ok(None);
+ };
+ let orig_mandate = state
+ .store
+ .find_mandate_by_merchant_id_mandate_id(
+ resp.merchant_id.as_ref(),
+ mandate_id,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
+ let mandate = match orig_mandate.mandate_type {
+ storage_enums::MandateType::SingleUse => state
+ .store
+ .update_mandate_by_merchant_id_mandate_id(
+ &resp.merchant_id,
+ mandate_id,
+ storage::MandateUpdate::StatusUpdate {
+ mandate_status: storage_enums::MandateStatus::Revoked,
+ },
+ orig_mandate,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
+ storage_enums::MandateType::MultiUse => state
+ .store
+ .update_mandate_by_merchant_id_mandate_id(
+ &resp.merchant_id,
+ mandate_id,
+ storage::MandateUpdate::CaptureAmountUpdate {
+ amount_captured: Some(
+ orig_mandate.amount_captured.unwrap_or(0)
+ + resp.request.get_amount(),
+ ),
+ },
+ orig_mandate,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
+ }?;
+ metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ mandate.connector,
+ )],
+ );
+ Ok(Some(mandate_id.clone()))
+ }
+ None => {
+ let Some(_mandate_details) = resp.request.get_setup_mandate_details() else {
+ return Ok(None);
+ };
+ let (mandate_reference, network_txn_id) = match &response {
+ types::PaymentsResponseData::TransactionResponse {
+ mandate_reference,
+ network_txn_id,
+ ..
+ } => (mandate_reference.clone(), network_txn_id.clone()),
+ _ => (None, None),
+ };
+
+ let mandate_ids = mandate_reference
+ .as_ref()
+ .map(|md| {
+ md.encode_to_value()
+ .change_context(errors::ApiErrorResponse::MandateSerializationFailed)
+ .map(masking::Secret::new)
+ })
+ .transpose()?;
+
+ let Some(new_mandate_data) = payment_helper::generate_mandate(
+ resp.merchant_id.clone(),
+ resp.payment_id.clone(),
+ resp.connector.clone(),
+ resp.request.get_setup_mandate_details().cloned(),
+ customer_id,
+ pm_id.get_required_value("payment_method_id")?,
+ mandate_ids,
+ network_txn_id,
+ get_insensitive_payment_method_data_if_exists(resp),
+ mandate_reference,
+ merchant_connector_id,
+ )?
+ else {
+ return Ok(None);
+ };
+
+ let connector = new_mandate_data.connector.clone();
+ logger::debug!("{:?}", new_mandate_data);
+
+ let res_mandate_id = new_mandate_data.mandate_id.clone();
+
+ state
+ .store
+ .insert_mandate(new_mandate_data, storage_scheme)
+ .await
+ .to_duplicate_response(errors::ApiErrorResponse::DuplicateMandate)?;
+ metrics::MANDATE_COUNT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes("connector", connector)],
+ );
+ Ok(Some(res_mandate_id))
+ }
}
- Ok(resp)
}
#[instrument(skip(state))]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index b9a8795aa54..33002dd2cbd 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -120,7 +120,7 @@ where
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Ctx>,
- FData: Send + Sync,
+ FData: Send + Sync + Clone,
Ctx: PaymentMethodRetrieve,
{
let operation: BoxedOperation<'_, F, Req, Ctx> = Box::new(operation);
@@ -274,11 +274,11 @@ where
req_state,
&merchant_account,
&key_store,
- connector,
+ connector.clone(),
&operation,
&mut payment_data,
&customer,
- call_connector_action,
+ call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload,
@@ -295,6 +295,18 @@ where
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
+
+ operation
+ .to_post_update_tracker()?
+ .save_pm_and_mandate(
+ state,
+ &router_data,
+ &merchant_account,
+ &key_store,
+ &mut payment_data,
+ )
+ .await?;
+
operation
.to_post_update_tracker()?
.update_tracker(
@@ -334,7 +346,7 @@ where
&operation,
&mut payment_data,
&customer,
- call_connector_action,
+ call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload,
@@ -362,7 +374,7 @@ where
req_state,
&mut payment_data,
connectors,
- connector_data,
+ connector_data.clone(),
router_data,
&merchant_account,
&key_store,
@@ -384,6 +396,18 @@ where
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
+
+ operation
+ .to_post_update_tracker()?
+ .save_pm_and_mandate(
+ state,
+ &router_data,
+ &merchant_account,
+ &key_store,
+ &mut payment_data,
+ )
+ .await?;
+
operation
.to_post_update_tracker()?
.update_tracker(
@@ -698,7 +722,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, Ctx>(
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
- FData: Send + Sync,
+ FData: Send + Sync + Clone,
Op: Operation<F, Req, Ctx> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
Res: transformers::ToResponse<PaymentData<F>, Op>,
@@ -1367,16 +1391,7 @@ where
// and rely on previous status set in router_data
router_data.status = payment_data.payment_attempt.status;
router_data
- .decide_flows(
- state,
- &connector,
- customer,
- call_connector_action,
- merchant_account,
- connector_request,
- key_store,
- payment_data.payment_intent.profile_id.clone(),
- )
+ .decide_flows(state, &connector, call_connector_action, connector_request)
.await
} else {
Ok(router_data)
@@ -1499,12 +1514,8 @@ where
let res = router_data.decide_flows(
state,
&session_connector_data.connector,
- customer,
CallConnectorAction::Trigger,
- merchant_account,
None,
- key_store,
- payment_data.payment_intent.profile_id.clone(),
);
join_handlers.push(res);
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 03cba29d025..59c0b687d64 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -44,12 +44,8 @@ pub trait Feature<F, T> {
self,
state: &AppState,
connector: &api::ConnectorData,
- maybe_customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- key_store: &domain::MerchantKeyStore,
- profile_id: Option<String>,
) -> 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 43e36847eb9..ffa11fdb0f5 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -49,12 +49,8 @@ impl Feature<api::Approve, types::PaymentsApproveData>
self,
_state: &AppState,
_connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
_call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
_connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> 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 10a4206a2b9..e44456fb1c7 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -61,12 +61,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
mut self,
state: &AppState,
connector: &api::ConnectorData,
- maybe_customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- key_store: &domain::MerchantKeyStore,
- profile_id: Option<String>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
@@ -78,7 +74,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
- let mut resp = services::execute_connector_processing_step(
+ let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
@@ -89,98 +85,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
.to_payment_failed_response()?;
metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
-
- let is_mandate = resp.request.setup_mandate_details.is_some();
-
- if is_mandate {
- let (payment_method_id, payment_method_status) =
- Box::pin(tokenization::save_payment_method(
- state,
- connector,
- resp.to_owned(),
- maybe_customer,
- merchant_account,
- self.request.payment_method_type,
- key_store,
- Some(resp.request.amount),
- Some(resp.request.currency),
- profile_id,
- ))
- .await?;
-
- resp.payment_method_id = payment_method_id.clone();
- resp.payment_method_status = payment_method_status;
-
- Ok(mandate::mandate_procedure(
- state,
- resp,
- maybe_customer,
- payment_method_id,
- connector.merchant_connector_id.clone(),
- merchant_account.storage_scheme,
- )
- .await?)
- } else {
- let response = resp.clone();
-
- logger::info!("Call to save_payment_method in locker");
-
- let pm = Box::pin(tokenization::save_payment_method(
- state,
- connector,
- response,
- maybe_customer,
- merchant_account,
- self.request.payment_method_type,
- key_store,
- Some(resp.request.amount),
- Some(resp.request.currency),
- profile_id,
- ))
- .await;
-
- match pm {
- Ok((payment_method_id, payment_method_status)) => {
- resp.payment_method_id = payment_method_id.clone();
- resp.payment_method_status = payment_method_status;
- }
- Err(err) => logger::error!("Save pm to locker failed : {err:?}"),
- }
-
- Ok(resp)
- }
-
- // Async locker code (Commenting out the code for near future refactors)
- // logger::info!("Call to save_payment_method in locker");
- // let _task_handle = tokio::spawn(
- // async move {
- // logger::info!("Starting async call to save_payment_method in locker");
- //
- // let result = Box::pin(tokenization::save_payment_method(
- // &state,
- // &connector,
- // response,
- // &maybe_customer,
- // &merchant_account,
- // self.request.payment_method_type,
- // &key_store,
- // Some(resp.request.amount),
- // Some(resp.request.currency),
- // ))
- // .await;
- //
- // if let Err(err) = result {
- // logger::error!(
- // "Asynchronously saving card in locker failed : {:?}",
- // err
- // );
- // }
- // }
- // .in_current_span(),
- // );
- //
- // Ok(resp)
- // }
+ Ok(resp)
} else {
Ok(self.clone())
}
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 5814b1cafb1..5f802a0bbe8 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -48,12 +48,8 @@ impl Feature<api::Void, types::PaymentsCancelData>
self,
state: &AppState,
connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> 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 5f64014bce7..56ae6500c35 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -49,12 +49,8 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
self,
state: &AppState,
connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> 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 e64240387d2..baf4190395f 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -63,12 +63,8 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
mut self,
state: &AppState,
connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
index 99f8e4831bb..e702483022c 100644
--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
@@ -56,12 +56,8 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat
self,
state: &AppState,
connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> 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 6463e87279b..f410b65f076 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -52,12 +52,8 @@ impl Feature<api::PSync, types::PaymentsSyncData>
mut self,
state: &AppState,
connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> 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 4157edf8d0a..89c1585fca1 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -48,12 +48,8 @@ impl Feature<api::Reject, types::PaymentsRejectData>
self,
_state: &AppState,
_connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
_call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
_connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> 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 7e15e2ed3f9..3d21aa732de 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -53,12 +53,8 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
self,
state: &routes::AppState,
connector: &api::ConnectorData,
- customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- _merchant_account: &domain::MerchantAccount,
_connector_request: Option<services::Request>,
- _key_store: &domain::MerchantKeyStore,
- _profile_id: Option<String>,
) -> RouterResult<Self> {
metrics::SESSION_TOKEN_CREATED.add(
&metrics::CONTEXT,
@@ -68,14 +64,8 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
connector.connector_name.to_string(),
)],
);
- self.decide_flow(
- state,
- connector,
- customer,
- Some(true),
- call_connector_action,
- )
- .await
+ self.decide_flow(state, connector, Some(true), call_connector_action)
+ .await
}
async fn add_access_token<'a>(
@@ -521,7 +511,6 @@ impl types::PaymentsSessionRouterData {
&'b self,
state: &'a routes::AppState,
connector: &api::ConnectorData,
- _customer: &Option<domain::Customer>,
_confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<Self> {
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index ff77efa7c46..6a810e9b3dd 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -1,14 +1,10 @@
-use api_models::enums::{PaymentMethod, PaymentMethodType};
use async_trait::async_trait;
-use error_stack::ResultExt;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
- configs::settings,
core::{
- errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
+ errors::{self, ConnectorErrorExt, RouterResult},
mandate,
- payment_methods::cards,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
@@ -57,76 +53,26 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
self,
state: &AppState,
connector: &api::ConnectorData,
- maybe_customer: &Option<domain::Customer>,
call_connector_action: payments::CallConnectorAction,
- merchant_account: &domain::MerchantAccount,
connector_request: Option<services::Request>,
- key_store: &domain::MerchantKeyStore,
- profile_id: Option<String>,
) -> RouterResult<Self> {
- if let Some(mandate_id) = self
- .request
- .setup_mandate_details
- .as_ref()
- .and_then(|mandate_data| mandate_data.update_mandate_id.clone())
- {
- Box::pin(self.update_mandate_flow(
- state,
- merchant_account,
- mandate_id,
- connector,
- key_store,
- call_connector_action,
- &state.conf.mandates.update_mandate_supported,
- connector_request,
- maybe_customer,
- profile_id,
- ))
- .await
- } else {
- let connector_integration: services::BoxedConnectorIntegration<
- '_,
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
-
- let mut resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- &self,
- call_connector_action.clone(),
- connector_request,
- )
- .await
- .to_setup_mandate_failed_response()?;
-
- let (pm_id, payment_method_status) = Box::pin(tokenization::save_payment_method(
- state,
- connector,
- resp.to_owned(),
- maybe_customer,
- merchant_account,
- self.request.payment_method_type,
- key_store,
- resp.request.amount,
- Some(resp.request.currency),
- profile_id,
- ))
- .await?;
+ let connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
- resp.payment_method_id = pm_id.clone();
- resp.payment_method_status = payment_method_status;
- mandate::mandate_procedure(
- state,
- resp,
- maybe_customer,
- pm_id,
- connector.merchant_connector_id.clone(),
- merchant_account.storage_scheme,
- )
- .await
- }
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &self,
+ call_connector_action.clone(),
+ connector_request,
+ )
+ .await
+ .to_setup_mandate_failed_response()?;
+ Ok(resp)
}
async fn add_access_token<'a>(
@@ -210,222 +156,6 @@ impl TryFrom<types::SetupMandateRequestData> for types::ConnectorCustomerData {
}
}
-#[allow(clippy::too_many_arguments)]
-impl types::SetupMandateRouterData {
- pub async fn decide_flow<'a, 'b>(
- &'b self,
- state: &'a AppState,
- connector: &api::ConnectorData,
- maybe_customer: &Option<domain::Customer>,
- confirm: Option<bool>,
- call_connector_action: payments::CallConnectorAction,
- merchant_account: &domain::MerchantAccount,
- key_store: &domain::MerchantKeyStore,
- profile_id: Option<String>,
- ) -> RouterResult<Self> {
- match confirm {
- Some(true) => {
- let connector_integration: services::BoxedConnectorIntegration<
- '_,
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
- let mut resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- self,
- call_connector_action,
- None,
- )
- .await
- .to_setup_mandate_failed_response()?;
-
- let payment_method_type = self.request.payment_method_type;
-
- let (pm_id, payment_method_status) = Box::pin(tokenization::save_payment_method(
- state,
- connector,
- resp.to_owned(),
- maybe_customer,
- merchant_account,
- payment_method_type,
- key_store,
- resp.request.amount,
- Some(resp.request.currency),
- profile_id,
- ))
- .await?;
-
- resp.payment_method_id = pm_id.clone();
- resp.payment_method_status = payment_method_status;
-
- Ok(mandate::mandate_procedure(
- state,
- resp,
- maybe_customer,
- pm_id,
- connector.merchant_connector_id.clone(),
- merchant_account.storage_scheme,
- )
- .await?)
- }
- _ => Ok(self.clone()),
- }
- }
-
- async fn update_mandate_flow(
- self,
- state: &AppState,
- merchant_account: &domain::MerchantAccount,
- mandate_id: String,
- connector: &api::ConnectorData,
- key_store: &domain::MerchantKeyStore,
- call_connector_action: payments::CallConnectorAction,
- supported_connectors_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
- connector_request: Option<services::Request>,
- maybe_customer: &Option<domain::Customer>,
- profile_id: Option<String>,
- ) -> RouterResult<Self> {
- let payment_method_type = self.request.payment_method_type;
-
- let payment_method = self.request.payment_method_data.get_payment_method();
- let supported_connectors_config = payment_method.zip(payment_method_type).map_or_else(
- || {
- if payment_method == Some(PaymentMethod::Card) {
- cards::filter_pm_based_on_update_mandate_support_for_connector(
- supported_connectors_for_update_mandate,
- &PaymentMethod::Card,
- &PaymentMethodType::Credit,
- connector.connector_name,
- ) && cards::filter_pm_based_on_update_mandate_support_for_connector(
- supported_connectors_for_update_mandate,
- &PaymentMethod::Card,
- &PaymentMethodType::Debit,
- connector.connector_name,
- )
- } else {
- false
- }
- },
- |(pm, pmt)| {
- cards::filter_pm_based_on_update_mandate_support_for_connector(
- supported_connectors_for_update_mandate,
- &pm,
- &pmt,
- connector.connector_name,
- )
- },
- );
- if supported_connectors_config {
- let connector_integration: services::BoxedConnectorIntegration<
- '_,
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
-
- let resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- &self,
- call_connector_action.clone(),
- connector_request,
- )
- .await
- .to_setup_mandate_failed_response()?;
- let pm_id = Box::pin(tokenization::save_payment_method(
- state,
- connector,
- resp.to_owned(),
- maybe_customer,
- merchant_account,
- self.request.payment_method_type,
- key_store,
- resp.request.amount,
- Some(resp.request.currency),
- profile_id,
- ))
- .await?
- .0;
- let mandate = state
- .store
- .find_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
- &mandate_id,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
-
- let profile_id = mandate::helpers::get_profile_id_for_mandate(
- state,
- merchant_account,
- mandate.clone(),
- )
- .await?;
- match resp.response {
- Ok(types::PaymentsResponseData::TransactionResponse { .. }) => {
- let connector_integration: services::BoxedConnectorIntegration<
- '_,
- types::api::MandateRevoke,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
- > = connector.connector.get_connector_integration();
- let merchant_connector_account = helpers::get_merchant_connector_account(
- state,
- &merchant_account.merchant_id,
- None,
- key_store,
- &profile_id,
- &mandate.connector,
- mandate.merchant_connector_id.as_ref(),
- )
- .await?;
-
- let router_data = mandate::utils::construct_mandate_revoke_router_data(
- merchant_connector_account,
- merchant_account,
- mandate.clone(),
- )
- .await?;
-
- let _response = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- call_connector_action,
- None,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- // TODO:Add the revoke mandate task to process tracker
- mandate::update_mandate_procedure(
- state,
- resp,
- mandate,
- &merchant_account.merchant_id,
- pm_id,
- merchant_account.storage_scheme,
- )
- .await
- }
- Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unexpected response received")?,
- Err(_) => Ok(resp),
- }
- } else {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: format!(
- "Update Mandate flow not implemented for the connector {:?}",
- connector.connector_name
- ),
- }
- .into())
- }
- }
-}
-
impl mandate::MandateBehaviour for types::SetupMandateRequestData {
fn get_amount(&self) -> i64 {
0
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index de2fdd99b7b..c8763584ccc 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1247,7 +1247,7 @@ pub(crate) async fn get_payment_method_create_request(
payment_method_data: Option<&domain::PaymentMethodData>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
- customer: &domain::Customer,
+ customer_id: &Option<String>,
billing_name: Option<masking::Secret<String>>,
) -> RouterResult<api::PaymentMethodCreate> {
match payment_method_data {
@@ -1265,7 +1265,6 @@ pub(crate) async fn get_payment_method_create_request(
card_issuer: card.card_issuer.clone(),
card_type: card.card_type.clone(),
};
- let customer_id = customer.customer_id.clone();
let payment_method_request = api::PaymentMethodCreate {
payment_method: Some(payment_method),
payment_method_type,
@@ -1277,7 +1276,7 @@ pub(crate) async fn get_payment_method_create_request(
wallet: None,
card: Some(card_detail),
metadata: None,
- customer_id: Some(customer_id),
+ customer_id: customer_id.clone(),
card_network: card
.card_network
.as_ref()
@@ -1299,7 +1298,7 @@ pub(crate) async fn get_payment_method_create_request(
wallet: None,
card: None,
metadata: None,
- customer_id: Some(customer.customer_id.to_owned()),
+ customer_id: customer_id.clone(),
card_network: None,
client_secret: None,
payment_method_data: None,
@@ -2618,7 +2617,7 @@ pub fn generate_mandate(
payment_id: String,
connector: String,
setup_mandate_details: Option<MandateData>,
- customer: &Option<domain::Customer>,
+ customer_id: &Option<String>,
payment_method_id: String,
connector_mandate_id: Option<pii::SecretSerdeValue>,
network_txn_id: Option<String>,
@@ -2626,8 +2625,8 @@ pub fn generate_mandate(
mandate_reference: Option<MandateReference>,
merchant_connector_id: Option<String>,
) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> {
- match (setup_mandate_details, customer) {
- (Some(data), Some(cus)) => {
+ match (setup_mandate_details, customer_id) {
+ (Some(data), Some(cus_id)) => {
let mandate_id = utils::generate_id(consts::ID_LENGTH, "man");
// The construction of the mandate new must be visible
@@ -2638,7 +2637,7 @@ pub fn generate_mandate(
.get_required_value("customer_acceptance")?;
new_mandate
.set_mandate_id(mandate_id)
- .set_customer_id(cus.customer_id.clone())
+ .set_customer_id(cus_id.clone())
.set_merchant_id(merchant_id)
.set_original_payment_id(Some(payment_id))
.set_payment_method_id(payment_method_id)
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 6b04c500dc1..d4590782b0a 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -212,7 +212,7 @@ pub trait UpdateTracker<F, D, Req, Ctx: PaymentMethodRetrieve>: Send {
}
#[async_trait]
-pub trait PostUpdateTracker<F, D, R>: Send {
+pub trait PostUpdateTracker<F, D, R: Send>: Send {
async fn update_tracker<'b>(
&'b self,
db: &'b AppState,
@@ -222,7 +222,21 @@ pub trait PostUpdateTracker<F, D, R>: Send {
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<D>
where
- F: 'b + Send;
+ F: 'b + Send + Sync;
+
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ _state: &AppState,
+ _resp: &types::RouterData<F, R, PaymentsResponseData>,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ _payment_data: &mut PaymentData<F>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ Ok(())
+ }
}
#[async_trait]
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index b96cf483236..4580181d394 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -15,7 +15,7 @@ use super::{Operation, PostUpdateTracker};
use crate::{
connector::utils::PaymentResponseRouterData,
core::{
- errors::{self, RouterResult, StorageErrorExt},
+ errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate,
payment_methods::{self, PaymentMethodRetrieve},
payments::{
@@ -24,6 +24,7 @@ use crate::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
},
+ tokenization,
types::MultipleCaptureData,
PaymentData,
},
@@ -31,7 +32,7 @@ use crate::{
},
routes::{metrics, AppState},
types::{
- self, api,
+ self, api, domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
CaptureSyncResponse, ErrorResponse,
@@ -42,12 +43,12 @@ use crate::{
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(
operations = "post_update_tracker",
- flow = "sync_data, authorize_data, cancel_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data"
+ flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data"
)]
pub struct PaymentResponse;
#[async_trait]
-impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData>
+impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData>
for PaymentResponse
{
async fn update_tracker<'b>(
@@ -63,7 +64,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>>
where
- F: 'b + Send,
+ F: 'b,
{
payment_data.mandate_id = payment_data
.mandate_id
@@ -80,6 +81,151 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData
Ok(payment_data)
}
+
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ state: &AppState,
+ resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ let customer_id = payment_data.payment_intent.customer_id.clone();
+ let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
+ let profile_id = payment_data.payment_intent.profile_id.clone();
+
+ let connector_name = payment_data
+ .payment_attempt
+ .connector
+ .clone()
+ .ok_or_else(|| {
+ logger::error!("Missing required Param connector_name");
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "connector_name",
+ }
+ })?;
+ let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
+ let billing_name = resp
+ .address
+ .get_payment_method_billing()
+ .and_then(|billing_details| billing_details.address.as_ref())
+ .and_then(|address| address.get_optional_full_name());
+
+ let save_payment_call_future = Box::pin(tokenization::save_payment_method(
+ state,
+ connector_name.clone(),
+ merchant_connector_id.clone(),
+ save_payment_data,
+ customer_id.clone(),
+ merchant_account,
+ resp.request.payment_method_type,
+ key_store,
+ Some(resp.request.amount),
+ Some(resp.request.currency),
+ profile_id,
+ billing_name.clone(),
+ ));
+
+ let is_connector_mandate = resp.request.customer_acceptance.is_some()
+ && matches!(
+ resp.request.setup_future_usage,
+ Some(enums::FutureUsage::OffSession)
+ );
+
+ let is_legacy_mandate = resp.request.setup_mandate_details.is_some()
+ && matches!(
+ resp.request.setup_future_usage,
+ Some(enums::FutureUsage::OffSession)
+ );
+
+ if is_legacy_mandate {
+ // Mandate is created on the application side and at the connector.
+ let (payment_method_id, _payment_method_status) = save_payment_call_future.await?;
+
+ let mandate_id = mandate::mandate_procedure(
+ state,
+ resp,
+ &customer_id.clone(),
+ payment_method_id.clone(),
+ merchant_connector_id.clone(),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ payment_data.payment_attempt.payment_method_id = payment_method_id;
+ payment_data.payment_attempt.mandate_id = mandate_id;
+ Ok(())
+ } else if is_connector_mandate {
+ // The mandate is created on connector's end.
+ let (payment_method_id, _payment_method_status) = save_payment_call_future.await?;
+ payment_data.payment_attempt.payment_method_id = payment_method_id;
+ Ok(())
+ } else {
+ // Save card flow
+ let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
+ let merchant_account = merchant_account.clone();
+ let key_store = key_store.clone();
+ let state = state.clone();
+ let customer_id = payment_data.payment_intent.customer_id.clone();
+ let profile_id = payment_data.payment_intent.profile_id.clone();
+
+ let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
+ let payment_attempt = payment_data.payment_attempt.clone();
+
+ let amount = resp.request.amount;
+ let currency = resp.request.currency;
+ let payment_method_type = resp.request.payment_method_type;
+ let storage_scheme = merchant_account.clone().storage_scheme;
+
+ logger::info!("Call to save_payment_method in locker");
+ let _task_handle = tokio::spawn(
+ async move {
+ logger::info!("Starting async call to save_payment_method in locker");
+
+ let result = Box::pin(tokenization::save_payment_method(
+ &state,
+ connector_name,
+ merchant_connector_id,
+ save_payment_data,
+ customer_id,
+ &merchant_account,
+ payment_method_type,
+ &key_store,
+ Some(amount),
+ Some(currency),
+ profile_id,
+ billing_name,
+ ))
+ .await;
+
+ if let Err(err) = result {
+ logger::error!("Asynchronously saving card in locker failed : {:?}", err);
+ } else if let Ok((payment_method_id, _pm_status)) = result {
+ let payment_attempt_update =
+ storage::PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
+ payment_method_id,
+ updated_by: storage_scheme.clone().to_string(),
+ };
+ let respond = state
+ .store
+ .update_payment_attempt_with_attempt_id(
+ payment_attempt,
+ payment_attempt_update,
+ storage_scheme,
+ )
+ .await;
+ if let Err(err) = respond {
+ logger::error!("Error updating payment attempt: {:?}", err);
+ };
+ }
+ }
+ .in_current_span(),
+ );
+ Ok(())
+ }
+ }
}
#[async_trait]
@@ -234,6 +380,28 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
))
.await
}
+
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ state: &AppState,
+ resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ update_payment_method_status_and_ntid(
+ state,
+ payment_data,
+ resp.status,
+ resp.response.clone(),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ Ok(())
+ }
}
#[async_trait]
@@ -411,6 +579,67 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
Ok(payment_data)
}
+
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ state: &AppState,
+ resp: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ let billing_name = resp
+ .address
+ .get_payment_method_billing()
+ .and_then(|billing_details| billing_details.address.as_ref())
+ .and_then(|address| address.get_optional_full_name());
+ let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
+ let customer_id = payment_data.payment_intent.customer_id.clone();
+ let profile_id = payment_data.payment_intent.profile_id.clone();
+ let connector_name = payment_data
+ .payment_attempt
+ .connector
+ .clone()
+ .ok_or_else(|| {
+ logger::error!("Missing required Param connector_name");
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "connector_name",
+ }
+ })?;
+ let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
+ let (payment_method_id, _payment_method_status) =
+ Box::pin(tokenization::save_payment_method(
+ state,
+ connector_name,
+ merchant_connector_id.clone(),
+ save_payment_data,
+ customer_id.clone(),
+ merchant_account,
+ resp.request.payment_method_type,
+ key_store,
+ resp.request.amount,
+ Some(resp.request.currency),
+ profile_id,
+ billing_name,
+ ))
+ .await?;
+
+ let mandate_id = mandate::mandate_procedure(
+ state,
+ resp,
+ &customer_id,
+ payment_method_id.clone(),
+ merchant_connector_id.clone(),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ payment_data.payment_attempt.payment_method_id = payment_method_id;
+ payment_data.payment_attempt.mandate_id = mandate_id;
+ Ok(())
+ }
}
#[async_trait]
@@ -437,6 +666,28 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
))
.await
}
+
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ state: &AppState,
+ resp: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ update_payment_method_status_and_ntid(
+ state,
+ payment_data,
+ resp.status,
+ resp.response.clone(),
+ merchant_account.storage_scheme,
+ )
+ .await?;
+ Ok(())
+ }
}
#[instrument(skip_all)]
@@ -587,7 +838,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
let payment_attempt_update =
storage::PaymentAttemptUpdate::PreprocessingUpdate {
status: updated_attempt_status,
- payment_method_id: router_data.payment_method_id,
+ payment_method_id: payment_data
+ .payment_attempt
+ .payment_method_id
+ .clone(),
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
@@ -642,7 +896,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
}
- let payment_method_id = router_data.payment_method_id.clone();
+ let payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
utils::add_apple_pay_payment_status_metrics(
router_data.status,
@@ -677,10 +931,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.request
.get_amount_capturable(&payment_data, updated_attempt_status),
payment_method_id,
- mandate_id: payment_data
- .mandate_id
- .clone()
- .and_then(|mandate| mandate.mandate_id),
+ mandate_id: payment_data.payment_attempt.mandate_id.clone(),
connector_metadata,
payment_token: None,
error_code: error_status.clone(),
@@ -862,14 +1113,6 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
},
};
- update_payment_method_status_and_ntid(
- state,
- &mut payment_data,
- router_data.status,
- router_data.response.clone(),
- storage_scheme,
- )
- .await?;
let m_db = state.clone().store;
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_payment_intent_update = payment_intent_update.clone();
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 5bf6b2e7013..304e6edd62e 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -29,38 +29,62 @@ use crate::{
utils::{generate_id, OptionExt},
};
+pub struct SavePaymentMethodData<Req> {
+ request: Req,
+ response: Result<types::PaymentsResponseData, types::ErrorResponse>,
+ payment_method_token: Option<types::PaymentMethodToken>,
+ payment_method: PaymentMethod,
+ attempt_status: common_enums::AttemptStatus,
+}
+
+impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>>
+ for SavePaymentMethodData<Req>
+{
+ fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self {
+ Self {
+ request: router_data.request.clone(),
+ response: router_data.response.clone(),
+ payment_method_token: router_data.payment_method_token.clone(),
+ payment_method: router_data.payment_method,
+ attempt_status: router_data.status,
+ }
+ }
+}
+
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
-pub async fn save_payment_method<F: Clone, FData>(
+pub async fn save_payment_method<FData>(
state: &AppState,
- connector: &api::ConnectorData,
- resp: types::RouterData<F, FData, types::PaymentsResponseData>,
- maybe_customer: &Option<domain::Customer>,
+ connector_name: String,
+ merchant_connector_id: Option<String>,
+ save_payment_method_data: SavePaymentMethodData<FData>,
+ customer_id: Option<String>,
merchant_account: &domain::MerchantAccount,
payment_method_type: Option<storage_enums::PaymentMethodType>,
key_store: &domain::MerchantKeyStore,
amount: Option<i64>,
currency: Option<storage_enums::Currency>,
profile_id: Option<String>,
+ billing_name: Option<masking::Secret<String>>,
) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
where
- FData: mandate::MandateBehaviour,
+ FData: mandate::MandateBehaviour + Clone,
{
let mut pm_status = None;
- match resp.response {
+ match save_payment_method_data.response {
Ok(responses) => {
let db = &*state.store;
let token_store = state
.conf
.tokenization
.0
- .get(&connector.connector_name.to_string())
+ .get(&connector_name.to_string())
.map(|token_filter| token_filter.long_lived_token)
.unwrap_or(false);
- let network_transaction_id = match responses.clone() {
+ let network_transaction_id = match &responses {
types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
- network_txn_id
+ network_txn_id.clone()
}
_ => None,
};
@@ -82,7 +106,7 @@ where
.attach_printable("The pg_agnostic config was not found in the DB")?;
if &pg_agnostic.config == "true"
- && resp.request.get_setup_future_usage()
+ && save_payment_method_data.request.get_setup_future_usage()
== Some(storage_enums::FutureUsage::OffSession)
{
Some(network_transaction_id)
@@ -95,7 +119,7 @@ where
};
let connector_token = if token_store {
- let tokens = resp
+ let tokens = save_payment_method_data
.payment_method_token
.to_owned()
.get_required_value("payment_token")?;
@@ -107,17 +131,17 @@ where
})?
}
};
- Some((connector, token))
+ Some((connector_name, token))
} else {
None
};
- let mandate_data_customer_acceptance = resp
+ let mandate_data_customer_acceptance = save_payment_method_data
.request
.get_setup_mandate_details()
.and_then(|mandate_data| mandate_data.customer_acceptance.clone());
- let customer_acceptance = resp
+ let customer_acceptance = save_payment_method_data
.request
.get_customer_acceptance()
.or(mandate_data_customer_acceptance.clone().map(From::from))
@@ -139,8 +163,11 @@ where
}
_ => None,
};
- let check_for_mit_mandates = resp.request.get_setup_mandate_details().is_none()
- && resp
+ let check_for_mit_mandates = save_payment_method_data
+ .request
+ .get_setup_mandate_details()
+ .is_none()
+ && save_payment_method_data
.request
.get_setup_future_usage()
.map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession)
@@ -151,7 +178,7 @@ where
payment_method_type,
amount,
currency,
- connector.merchant_connector_id.clone(),
+ merchant_connector_id.clone(),
connector_mandate_id.clone(),
)
} else {
@@ -163,23 +190,16 @@ where
.attach_printable("Unable to serialize customer acceptance to value")?;
let pm_id = if customer_acceptance.is_some() {
- let customer = maybe_customer.to_owned().get_required_value("customer")?;
- let billing_name = resp
- .address
- .get_payment_method_billing()
- .and_then(|billing_details| billing_details.address.as_ref())
- .and_then(|address| address.get_optional_full_name());
-
let payment_method_create_request = helpers::get_payment_method_create_request(
- Some(&resp.request.get_payment_method_data()),
- Some(resp.payment_method),
+ Some(&save_payment_method_data.request.get_payment_method_data()),
+ Some(save_payment_method_data.payment_method),
payment_method_type,
- &customer,
+ &customer_id.clone(),
billing_name,
)
.await?;
+ let customer_id = customer_id.to_owned().get_required_value("customer_id")?;
let merchant_id = &merchant_account.merchant_id;
-
let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
skip_saving_card_in_locker(
merchant_account,
@@ -187,7 +207,9 @@ where
)
.await?
} else {
- pm_status = Some(common_enums::PaymentMethodStatus::from(resp.status));
+ pm_status = Some(common_enums::PaymentMethodStatus::from(
+ save_payment_method_data.attempt_status,
+ ));
Box::pin(save_in_locker(
state,
merchant_account,
@@ -280,7 +302,7 @@ where
payment_method_type,
amount,
currency,
- connector.merchant_connector_id.clone(),
+ merchant_connector_id.clone(),
connector_mandate_id.clone(),
)?;
@@ -297,7 +319,7 @@ where
payment_methods::cards::create_payment_method(
db,
&payment_method_create_request,
- &customer.customer_id,
+ customer_id.as_str(),
&resp.payment_method_id,
locker_id,
merchant_id,
@@ -371,7 +393,7 @@ where
payment_method_type,
amount,
currency,
- connector.merchant_connector_id.clone(),
+ merchant_connector_id.clone(),
connector_mandate_id.clone(),
)?;
@@ -390,7 +412,7 @@ where
payment_method_create_request.clone(),
key_store,
&merchant_account.merchant_id,
- &customer.customer_id,
+ customer_id.as_str(),
resp.metadata.clone().map(|val| val.expose()),
customer_acceptance,
locker_id,
@@ -413,7 +435,7 @@ where
payment_methods::cards::delete_card_from_locker(
state,
- &customer.customer_id,
+ customer_id.as_str(),
merchant_id,
existing_pm
.locker_id
@@ -426,7 +448,7 @@ where
state,
payment_method_create_request,
&card,
- customer.customer_id.clone(),
+ customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
@@ -516,7 +538,7 @@ where
payment_methods::cards::create_payment_method(
db,
&payment_method_create_request,
- &customer.customer_id,
+ customer_id.as_str(),
&resp.payment_method_id,
locker_id,
merchant_id,
@@ -683,7 +705,7 @@ pub async fn save_in_locker(
pub fn create_payment_method_metadata(
metadata: Option<&pii::SecretSerdeValue>,
- connector_token: Option<(&api::ConnectorData, String)>,
+ connector_token: Option<(String, String)>,
) -> RouterResult<Option<serde_json::Value>> {
let mut meta = match metadata {
None => serde_json::Map::new(),
@@ -698,7 +720,7 @@ pub fn create_payment_method_metadata(
};
Ok(connector_token.and_then(|connector_and_token| {
meta.insert(
- connector_and_token.0.connector_name.to_string(),
+ connector_and_token.0,
serde_json::Value::String(connector_and_token.1),
)
}))
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 6eda689c8da..1fd25f3dedb 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1433,6 +1433,13 @@ impl DataModelExt for PaymentAttemptUpdate {
error_message,
updated_by,
},
+ Self::PaymentMethodDetailsUpdate {
+ payment_method_id,
+ updated_by,
+ } => DieselPaymentAttemptUpdate::PaymentMethodDetailsUpdate {
+ payment_method_id,
+ updated_by,
+ },
Self::ConfirmUpdate {
amount,
currency,
@@ -1807,6 +1814,13 @@ impl DataModelExt for PaymentAttemptUpdate {
error_message,
updated_by,
},
+ DieselPaymentAttemptUpdate::PaymentMethodDetailsUpdate {
+ payment_method_id,
+ updated_by,
+ } => Self::PaymentMethodDetailsUpdate {
+ payment_method_id,
+ updated_by,
+ },
DieselPaymentAttemptUpdate::ResponseUpdate {
status,
connector,
|
2024-04-04T14:36:07Z
|
## 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 aims to make the locker call async(again). Moreover the main problem this PR solves is to adding `pm_id` in payment_attempt even in an async locker call. This is achieved by adding up a new function in `PostUpdateTracker` trait named as `save_pm_and_mandate`.
### 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)?
-->
Curls for the test cases:
1. Save Card payment
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Lhj81dmb5DH3dasSlnRy2LUAHIOc6LJDFSQxyLbrAS7HWS5Hxva2YOJTYea90wXw' \
--data-raw '
{
"amount": 150,
"currency": "USD",
"confirm": true,
"profile_id": "pro_I8QjDfpUKyQ0EBzKRWfp",
"capture_method": "automatic",
"customer_id": "cus_ssOCYK1qRIjeBfMhEy6A",
"amount_to_capture": 150,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5555 5555 5555 4444",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"phone_country_code": "+65",
"authentication_type": "no_three_ds",
"description": "Its my first payment request",
"return_url": "https://google.com",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"metadata": {},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari",
"last_name": "sundari"
}
}
}'
```
Response
```
{
"payment_id": "pay_htNp37U15sOwsXZPZ9Br",
"merchant_id": "merchant_1712724367",
"status": "succeeded",
"amount": 150,
"net_amount": 150,
"amount_capturable": 0,
"amount_received": 150,
"connector": "cybersource",
"client_secret": "pay_htNp37U15sOwsXZPZ9Br_secret_I56SQnEKoGQGyHhcIarl",
"created": "2024-04-11T05:07:46.740Z",
"currency": "USD",
"customer_id": "cus_ssOCYK1qRIjeBfMhEy6A",
"customer": {
"id": "cus_ssOCYK1qRIjeBfMhEy6A",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4444",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "555555",
"card_extended_bin": "55555555",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QD71AcirSSN1hroINifk",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": "sundari"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cus_ssOCYK1qRIjeBfMhEy6A",
"created_at": 1712812066,
"expires": 1712815666,
"secret": "epk_9ea82157d50e457c8f0d56c88f13b117"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7128120679866152903954",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_htNp37U15sOwsXZPZ9Br_1",
"payment_link": null,
"profile_id": "pro_I8QjDfpUKyQ0EBzKRWfp",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JGHsMWurht6srLkWsjO3",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-11T05:22:46.740Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null
}
```
Payment Retrieve
```
{
"payment_id": "pay_htNp37U15sOwsXZPZ9Br",
"merchant_id": "merchant_1712724367",
"status": "succeeded",
"amount": 150,
"net_amount": 150,
"amount_capturable": 0,
"amount_received": 150,
"connector": "cybersource",
"client_secret": "pay_htNp37U15sOwsXZPZ9Br_secret_I56SQnEKoGQGyHhcIarl",
"created": "2024-04-11T05:07:46.740Z",
"currency": "USD",
"customer_id": "cus_ssOCYK1qRIjeBfMhEy6A",
"customer": {
"id": "cus_ssOCYK1qRIjeBfMhEy6A",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4444",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "555555",
"card_extended_bin": "55555555",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QD71AcirSSN1hroINifk",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": "sundari"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7128120679866152903954",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_htNp37U15sOwsXZPZ9Br_1",
"payment_link": null,
"profile_id": "pro_I8QjDfpUKyQ0EBzKRWfp",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JGHsMWurht6srLkWsjO3",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-11T05:22:46.740Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_2ERfpXUJ7vYzqYSk3hdE",
"payment_method_status": "active"
}
```
2. Setup Mandate
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Lhj81dmb5DH3dasSlnRy2LUAHIOc6LJDFSQxyLbrAS7HWS5Hxva2YOJTYea90wXw' \
--data-raw '
{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "mandate_customer1",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "online"
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"card_cvc": "737"
}
},
"payment_type": "setup_mandate",
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "three_ds"
}'
```
Response
```
{
"payment_id": "pay_okrJvtehbXTDXcDydQnv",
"merchant_id": "merchant_1712724367",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_okrJvtehbXTDXcDydQnv_secret_Y0quTVIFHHwNV1fTLT2T",
"created": "2024-04-11T05:36:27.333Z",
"currency": "USD",
"customer_id": "mandate_customer1",
"customer": {
"id": "mandate_customer1",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "token_Xh7IwDTEFet4MJ3XCyYz",
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "mandate_customer1",
"created_at": 1712813787,
"expires": 1712817387,
"secret": "epk_b75613967b7e4965bad88d90704f985e"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7128137892656606404953",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_okrJvtehbXTDXcDydQnv_1",
"payment_link": null,
"profile_id": "pro_I8QjDfpUKyQ0EBzKRWfp",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JGHsMWurht6srLkWsjO3",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-11T05:51:27.333Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_WmIHJOFLVZYHH1GMSztb",
"payment_method_status": null
}
```
3. Recurring mandate
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Lhj81dmb5DH3dasSlnRy2LUAHIOc6LJDFSQxyLbrAS7HWS5Hxva2YOJTYea90wXw' \
--data-raw '
{
"amount": 499,
"currency": "USD",
"confirm": true,
"profile_id": "pro_I8QjDfpUKyQ0EBzKRWfp",
"capture_method": "automatic",
"customer_id": "mandate_customer1",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_WmIHJOFLVZYHH1GMSztb"
},
"payment_method": "card",
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "three_ds"
}'
```
Response:
```
{
"payment_id": "pay_mg9hJf7VjCYa50hpSrdG",
"merchant_id": "merchant_1712724367",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": "cybersource",
"client_secret": "pay_mg9hJf7VjCYa50hpSrdG_secret_EcNG9aGozUOBzs2vZhXj",
"created": "2024-04-11T05:39:34.990Z",
"currency": "USD",
"customer_id": "mandate_customer1",
"customer": {
"id": "mandate_customer1",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "mandate_customer1",
"created_at": 1712813974,
"expires": 1712817574,
"secret": "epk_381d81dec1eb4219a7ac9a072fd4402e"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7128139751946727304953",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_mg9hJf7VjCYa50hpSrdG_1",
"payment_link": null,
"profile_id": "pro_I8QjDfpUKyQ0EBzKRWfp",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JGHsMWurht6srLkWsjO3",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-11T05:54:34.990Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_WmIHJOFLVZYHH1GMSztb",
"payment_method_status": "active"
}
```
## Checklist
<!-- Put an `x` in 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
|
9bf16b1a0787f9badb4a6decd38e3e5d69a3ea51
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4121
|
Bug: [REFACTOR]: update Stripe API version in the API headers
### Bug Description
Stripe supports multiple api versions and each stripe merchant account has its own default api version based on the time the account has created. So whenever Hyperswitch calls stripe API, stripe will respond based on merchant's default version which might differ from the version which Hyperswitch has implemented. The current API version is not the compatible with our implementation. So we need to update the version according to current implementation.
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index dd8fc845e28..b85247607e0 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -34,7 +34,7 @@ use crate::{
pub mod auth_headers {
pub const STRIPE_API_VERSION: &str = "stripe-version";
- pub const STRIPE_VERSION: &str = "2023-10-16";
+ pub const STRIPE_VERSION: &str = "2022-11-15";
}
pub struct StripeAuthType {
|
2024-03-18T17:50:58Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Fixes https://github.com/juspay/hyperswitch/issues/4121
Stripe supports multiple api versions and each stripe merchant account has its own default api version based on the time the account has created. So whenever Hyperswitch calls stripe API, stripe will respond based on merchant's default version which might differ from the version which Hyperswitch has implemented. The current API version is not the compatible with our implementation. So we need to update the version according to current implementation.
### 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?
1. Run whole Stripe Postman collection
2. Create a stripe Card Payment Request
```
{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "stripe"
}
}
```
Response
```
{
"payment_id": "pay_cmmd8900wIRqd11y6kUL",
"merchant_id": "postman_merchant_GHAction_8953df12-7ed3-416a-9334-4c71f3e2672d",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_cmmd8900wIRqd11y6kUL_secret_gcsfaLqv8d1pMAq6xApL",
"created": "2024-03-15T10:59:51.115Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
},
"email": null
}
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1710500391,
"expires": 1710503991,
"secret": "epk_c5c1acf2bee0476182e5c46bcc1079c5"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3OuYUND5R7gDAGff1bwg1RSP",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3OuYUND5R7gDAGff1bwg1RSP",
"payment_link": null,
"profile_id": "pro_2x6hcEAjCQmaYxIpxO5V",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_IGo3sNcqXv7xd4POhiLS",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T11:14:51.115Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
Now in Stripe Dashboard search for the payment Under Developer -> Logs using `connector_transaction_id`
For that payment check the header-info , API-Version should be `"2022-11-15"`
Do Paymnet Retrieve for same Payment ID
Do a Refund
```
{
"payment_id": "{{payment_id}}",
"amount": 600,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Do Refund Retrieve
3. Create a payment with capture = manual
```
{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "stripe"
}
}
```
Capture it for same PI
Payment should get succeeded with `status = succeeded`
Again create a payment for capture = manual
Void a Paymnet - Payment should get cancelled with `status = cancelled`
4. Create a O Auth mandate payment with stripe cards
```
{
"amount": 0,
"currency": "USD",
"confirm": true,
"setup_future_usage": "off_session",
"customer_id": "cus_PAxm0MeCGM5TowgDKPc9",
"payment_type": "setup_mandate",
"payment_method": "card",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 7000,
"currency": "USD"
}
}
},
"payment_method_data": {
"card": {
"card_number": "4000000000000101",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "Chaser",
"last_name": "Dough"
},
"email": "example@juspay.in"
}
}
```
Response of 0 auth mandate
```
{
"payment_id": "pay_L8pXs9YkASVJBvSSd0M2",
"merchant_id": "postman_merchant_GHAction_5a2737e9-c107-411c-b458-8401b98e91ea",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe",
"client_secret": "pay_L8pXs9YkASVJBvSSd0M2_secret_oeTWqzB1O8kfVjzCeDDh",
"created": "2024-03-19T06:56:47.885Z",
"currency": "USD",
"customer_id": "cus_PAxm0MeCGM5TowgDKPc9",
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_e0ADcjvb5OXgrGw1nF73",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 7000,
"currency": "USD",
"start_date": null,
"end_date": null,
"metadata": null
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0101",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": "40000000",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"zip": "94122",
"state": "California",
"first_name": "Chaser",
"last_name": "Dough"
},
"phone": null,
"email": "example@juspay.in"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cus_PAxm0MeCGM5TowgDKPc9",
"created_at": 1710831407,
"expires": 1710835007,
"secret": "epk_0ac0213b300e4d5f87c98645f96f5b6e"
},
"manual_retry_allowed": false,
"connector_transaction_id": "seti_1OvwbMD5R7gDAGffdYIQlLqu",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "seti_1OvwbMD5R7gDAGffdYIQlLqu",
"payment_link": null,
"profile_id": "pro_dHIsgCLvmZZcFRgkt3xE",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_mJiXEB1oLi5HXKhWCt9A",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-19T07:11:47.885Z",
"fingerprint": null,
"payment_method_id": "pm_SO8UJG7uDvc8oC2KgDAc",
"payment_method_status": null
}
```
Check the version after the payment in stripe dashboard. API-Version should be `"2022-11-15"`
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
fcfd567bfe55747dcb05c88def96373a707f8c78
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4136
|
Bug: [GlobalSearch] - BE - escape reserved characters in global search query
escape these reserved character which will break the search query
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters
currently when you pass the reserved characters in global search, the query_string break and it throwing something went wrong
```
curl --location 'https://sandbox.hyperswitch.io/analytics/v1/search' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjQ0NjQyMjktNGI1OC00ODY5LThjODQtYWYxZTcwZWViMGRiIiwibWVyY2hhbnRfaWQiOiJqdXNwYXk3NTMiLCJyb2xlX2lkIjoibWVyY2hhbnRfYWRtaW4iLCJleHAiOjE3MTEwMjgwOTIsIm9yZ19pZCI6Im9yZ19YNXo3aGtSYzdmb2lpSU1lY3BudDIifQ.5mgjfo6--qkSKwqqrQgp0EenvCJQaGLm4SyDyOnu7NY' \
--header 'content-type: application/json' \
--data '{
"query": "Unexpected communication error with connector/acquirer"
}'
```
```json
{"error":{"type":"api","message":"Something went wrong","code":"HE_00"}}
```
hence moving the opensearch query to filter field under multi_match phrase which should ignore these reserved characters.
```
curl --location --request POST 'http://localhost:8080/analytics/v1/search/payment_attempts' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer *' \
--header 'content-type: application/json' \
--data-raw '{
"query": "Bearer auth (e.g. ",
"offset": 0,
"count": 10
}'
```
```json
{"count":1,"index":"payment_attempts","hits":[{"payment_id":"pay_YVRqba3s481F4MHN5Hv9","merchant_id":"merchant_1711008266","attempt_id":"pay_YVRqba3s481F4MHN5Hv9_1","status":"failure","amount":6540,"currency":"USD","save_to_locker":null,"connector":"stripe","error_message":"No error message","offer_amount":null,"surcharge_amount":null,"tax_amount":null,"payment_method_id":null,"payment_method":"card","connector_transaction_id":null,"capture_method":"automatic","capture_on":1662804672,"confirm":true,"authentication_type":"no_three_ds","created_at":1711008789,"modified_at":1711008790,"last_synced":1711008789,"cancellation_reason":null,"amount_to_capture":6540,"mandate_id":null,"browser_info":null,"error_code":"No error code","connector_metadata":null,"payment_experience":null,"payment_method_type":"credit","payment_method_data":"{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":\"joseph Doe\",\"card_extended_bin\":\"42424242\",\"authentication_data\":null,\"card_issuing_country\":null}}","error_reason":"You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.","multiple_capture_count":null,"amount_capturable":0,"merchant_connector_id":"mca_eQ5bf2NARvV0cMAHloyM","net_amount":6540,"unified_code":null,"unified_message":null,"mandate_data":null,"sign_flag":1}]}
```
```
curl --location --request POST 'http://localhost:8080/analytics/v1/search/payment_attempts' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer *' \
--header 'content-type: application/json' \
--data-raw '{
"query": "Unexpected communication error with connector/acquirer",
"offset": 0,
"count": 10
}'
```
```json
{"count":0,"index":"payment_attempts","hits":[]}
```
|
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index d9b8433ba63..4c42e96250b 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -81,7 +81,7 @@ pub async fn msearch_results(
for index in SearchIndex::iter() {
msearch_vector
.push(json!({"index": search_index_to_opensearch_index(index,&config.indexes)}).into());
- msearch_vector.push(json!({"query": {"bool": {"must": {"query_string": {"query": req.query}}, "filter": {"match_phrase": {"merchant_id": merchant_id}}}}}).into());
+ msearch_vector.push(json!({"query": {"bool": {"filter": [{"multi_match": {"type": "phrase", "query": req.query, "lenient": true}},{"match_phrase": {"merchant_id": merchant_id}}]}}}).into());
}
let response = client
@@ -128,7 +128,7 @@ pub async fn search_results(
.search(SearchParts::Index(&[&search_index_to_opensearch_index(req.index.clone(),&config.indexes)]))
.from(search_req.offset)
.size(search_req.count)
- .body(json!({"query": {"bool": {"must": {"query_string": {"query": search_req.query}}, "filter": {"match_phrase": {"merchant_id": merchant_id}}}}}))
+ .body(json!({"query": {"bool": {"filter": [{"multi_match": {"type": "phrase", "query": search_req.query, "lenient": true}},{"match_phrase": {"merchant_id": merchant_id}}]}}}))
.send()
.await
.map_err(|_| AnalyticsError::UnknownError)?;
|
2024-03-19T14:36:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
escape reserved characters in global search query
### 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
escape [reserved](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters) characters in global search query
## How did you test it?
```
curl --location --request POST 'http://localhost:8080/analytics/v1/search/payment_attempts' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer *' \
--header 'content-type: application/json' \
--data-raw '{
"query": "Bearer auth (e.g. ",
"offset": 0,
"count": 10
}'
```
```json
{"count":1,"index":"payment_attempts","hits":[{"payment_id":"pay_YVRqba3s481F4MHN5Hv9","merchant_id":"merchant_1711008266","attempt_id":"pay_YVRqba3s481F4MHN5Hv9_1","status":"failure","amount":6540,"currency":"USD","save_to_locker":null,"connector":"stripe","error_message":"No error message","offer_amount":null,"surcharge_amount":null,"tax_amount":null,"payment_method_id":null,"payment_method":"card","connector_transaction_id":null,"capture_method":"automatic","capture_on":1662804672,"confirm":true,"authentication_type":"no_three_ds","created_at":1711008789,"modified_at":1711008790,"last_synced":1711008789,"cancellation_reason":null,"amount_to_capture":6540,"mandate_id":null,"browser_info":null,"error_code":"No error code","connector_metadata":null,"payment_experience":null,"payment_method_type":"credit","payment_method_data":"{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":\"joseph Doe\",\"card_extended_bin\":\"42424242\",\"authentication_data\":null,\"card_issuing_country\":null}}","error_reason":"You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.","multiple_capture_count":null,"amount_capturable":0,"merchant_connector_id":"mca_eQ5bf2NARvV0cMAHloyM","net_amount":6540,"unified_code":null,"unified_message":null,"mandate_data":null,"sign_flag":1}]}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
944089d6914cb6bece9056f78b9aabf90e485151
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4112
|
Bug: [BUG] : [Stripe] make name mandatory
### Bug Description
Field called name in stripe Shipping address is not an optional at the stripe's end but it is optional in hyperswitch's stripe transformer
### Expected Behavior
Stripe transformer must treat name as a mandatory field
### Actual Behavior
Stripe transformer treats name as an optional field
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 45e2c795a0d..82dee21f7e6 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -117,7 +117,7 @@ pub struct PaymentIntentRequest {
pub setup_mandate_details: Option<StripeMandateRequest>,
pub description: Option<String>,
#[serde(flatten)]
- pub shipping: StripeShippingAddress,
+ pub shipping: Option<StripeShippingAddress>,
#[serde(flatten)]
pub billing: StripeBillingAddress,
#[serde(flatten)]
@@ -882,26 +882,33 @@ impl TryFrom<&api_models::enums::BankNames> for StripeBankNames {
}
fn validate_shipping_address_against_payment_method(
- shipping_address: &StripeShippingAddress,
+ shipping_address: &Option<StripeShippingAddress>,
payment_method: Option<&StripePaymentMethodType>,
) -> Result<(), error_stack::Report<errors::ConnectorError>> {
- if let Some(StripePaymentMethodType::AfterpayClearpay) = payment_method {
- let missing_fields = collect_missing_value_keys!(
- ("shipping.address.first_name", shipping_address.name),
- ("shipping.address.line1", shipping_address.line1),
- ("shipping.address.country", shipping_address.country),
- ("shipping.address.zip", shipping_address.zip)
- );
-
- if !missing_fields.is_empty() {
- return Err(errors::ConnectorError::MissingRequiredFields {
- field_names: missing_fields,
+ match payment_method {
+ Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address {
+ Some(address) => {
+ let missing_fields = collect_missing_value_keys!(
+ ("shipping.address.line1", address.line1),
+ ("shipping.address.country", address.country),
+ ("shipping.address.zip", address.zip)
+ );
+
+ if !missing_fields.is_empty() {
+ return Err(errors::ConnectorError::MissingRequiredFields {
+ field_names: missing_fields,
+ })
+ .into_report();
+ }
+ Ok(())
+ }
+ None => Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "shipping.address",
})
- .into_report();
- }
+ .into_report(),
+ },
+ _ => Ok(()),
}
-
- Ok(())
}
impl TryFrom<&api_models::payments::PayLaterData> for StripePaymentMethodType {
@@ -1717,23 +1724,27 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
let shipping_address = match item.get_optional_shipping() {
Some(shipping_details) => {
let shipping_address = shipping_details.address.as_ref();
- StripeShippingAddress {
+ Some(StripeShippingAddress {
city: shipping_address.and_then(|a| a.city.clone()),
country: shipping_address.and_then(|a| a.country),
line1: shipping_address.and_then(|a| a.line1.clone()),
line2: shipping_address.and_then(|a| a.line2.clone()),
zip: shipping_address.and_then(|a| a.zip.clone()),
state: shipping_address.and_then(|a| a.state.clone()),
- name: shipping_address.and_then(|a| {
- a.first_name.as_ref().map(|first_name| {
- format!(
- "{} {}",
- first_name.clone().expose(),
- a.last_name.clone().expose_option().unwrap_or_default()
- )
- .into()
+ name: shipping_address
+ .and_then(|a| {
+ a.first_name.as_ref().map(|first_name| {
+ format!(
+ "{} {}",
+ first_name.clone().expose(),
+ a.last_name.clone().expose_option().unwrap_or_default()
+ )
+ .into()
+ })
})
- }),
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "shipping_address.first_name",
+ })?,
phone: shipping_details.phone.as_ref().map(|p| {
format!(
"{}{}",
@@ -1742,9 +1753,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
)
.into()
}),
- }
+ })
}
- None => StripeShippingAddress::default(),
+ None => None,
};
let billing_address = match item.get_optional_billing() {
@@ -2930,7 +2941,7 @@ pub struct StripeShippingAddress {
#[serde(rename = "shipping[address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "shipping[name]")]
- pub name: Option<Secret<String>>,
+ pub name: Secret<String>,
#[serde(rename = "shipping[phone]")]
pub phone: Option<Secret<String>>,
}
@@ -3841,7 +3852,7 @@ mod test_validate_shipping_address_against_payment_method {
fn should_return_ok() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
- Some("name".to_string()),
+ "name".to_string(),
Some("line1".to_string()),
Some(CountryAlpha2::AD),
Some("zip".to_string()),
@@ -3851,7 +3862,7 @@ mod test_validate_shipping_address_against_payment_method {
//Act
let result = validate_shipping_address_against_payment_method(
- &stripe_shipping_address,
+ &Some(stripe_shipping_address),
Some(payment_method),
);
@@ -3859,39 +3870,11 @@ mod test_validate_shipping_address_against_payment_method {
assert!(result.is_ok());
}
- #[test]
- fn should_return_err_for_empty_name() {
- // Arrange
- let stripe_shipping_address = create_stripe_shipping_address(
- None,
- Some("line1".to_string()),
- Some(CountryAlpha2::AD),
- Some("zip".to_string()),
- );
-
- let payment_method = &StripePaymentMethodType::AfterpayClearpay;
-
- //Act
- let result = validate_shipping_address_against_payment_method(
- &stripe_shipping_address,
- Some(payment_method),
- );
-
- // Assert
- assert!(result.is_err());
- let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
- assert_eq!(missing_fields.len(), 1);
- assert_eq!(
- *missing_fields.first().unwrap(),
- "shipping.address.first_name"
- );
- }
-
#[test]
fn should_return_err_for_empty_line1() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
- Some("name".to_string()),
+ "name".to_string(),
None,
Some(CountryAlpha2::AD),
Some("zip".to_string()),
@@ -3901,7 +3884,7 @@ mod test_validate_shipping_address_against_payment_method {
//Act
let result = validate_shipping_address_against_payment_method(
- &stripe_shipping_address,
+ &Some(stripe_shipping_address),
Some(payment_method),
);
@@ -3916,7 +3899,7 @@ mod test_validate_shipping_address_against_payment_method {
fn should_return_err_for_empty_country() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
- Some("name".to_string()),
+ "name".to_string(),
Some("line1".to_string()),
None,
Some("zip".to_string()),
@@ -3926,7 +3909,7 @@ mod test_validate_shipping_address_against_payment_method {
//Act
let result = validate_shipping_address_against_payment_method(
- &stripe_shipping_address,
+ &Some(stripe_shipping_address),
Some(payment_method),
);
@@ -3941,7 +3924,7 @@ mod test_validate_shipping_address_against_payment_method {
fn should_return_err_for_empty_zip() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
- Some("name".to_string()),
+ "name".to_string(),
Some("line1".to_string()),
Some(CountryAlpha2::AD),
None,
@@ -3950,7 +3933,7 @@ mod test_validate_shipping_address_against_payment_method {
//Act
let result = validate_shipping_address_against_payment_method(
- &stripe_shipping_address,
+ &Some(stripe_shipping_address),
Some(payment_method),
);
@@ -3967,7 +3950,7 @@ mod test_validate_shipping_address_against_payment_method {
let expected_missing_field_names: Vec<&'static str> =
vec!["shipping.address.zip", "shipping.address.country"];
let stripe_shipping_address = create_stripe_shipping_address(
- Some("name".to_string()),
+ "name".to_string(),
Some("line1".to_string()),
None,
None,
@@ -3976,7 +3959,7 @@ mod test_validate_shipping_address_against_payment_method {
//Act
let result = validate_shipping_address_against_payment_method(
- &stripe_shipping_address,
+ &Some(stripe_shipping_address),
Some(payment_method),
);
@@ -3997,13 +3980,13 @@ mod test_validate_shipping_address_against_payment_method {
}
fn create_stripe_shipping_address(
- name: Option<String>,
+ name: String,
line1: Option<String>,
country: Option<CountryAlpha2>,
zip: Option<String>,
) -> StripeShippingAddress {
StripeShippingAddress {
- name: name.map(Secret::new),
+ name: Secret::new(name),
line1: line1.map(Secret::new),
country,
zip: zip.map(Secret::new),
|
2024-03-15T10:41:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Field called `name` in stripe Shipping address is not optional at the stripe's end. This PR makes it a mandatory field.
## Test Case
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{}}' \
--data-raw '{
"amount": 7000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "SE"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"order_details": {
"product_name": "Socks",
"amount": 7000,
"quantity": 1
}
},
"payment_method": "pay_later",
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"pay_later": {
"afterpay_clearpay_redirect": {
"billing_name": "Akshaya",
"billing_email": "example@example.com"
}
}
}
}'
```
Response
```
{
"error": {
"type": "invalid_request",
"message": "Missing required param: shipping_address.first_name",
"code": "IR_04"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4106
|
Bug: [FEATURE] [CYBERSOURCE/BOA] Add support for payment status ACCEPTED and CANCELLED
### Feature Description
The payment response must address the `ACCEPTED` and `CANCELLED` payment status from connectors Bankofamerica and Cybersource.
### Possible Implementation
Payment status `ACCEPTED` and `CANCELLED` should be added to `CybersourcePaymentStatus` and `BankofamericaPaymentStatus`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 8e30e2b0475..b9a14321025 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -896,6 +896,8 @@ pub enum BankofamericaPaymentStatus {
ServerError,
PendingAuthentication,
PendingReview,
+ Accepted,
+ Cancelled,
//PartialAuthorized, not being consumed yet.
}
@@ -921,9 +923,9 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus {
BankofamericaPaymentStatus::Succeeded | BankofamericaPaymentStatus::Transmitted => {
Self::Charged
}
- BankofamericaPaymentStatus::Voided | BankofamericaPaymentStatus::Reversed => {
- Self::Voided
- }
+ BankofamericaPaymentStatus::Voided
+ | BankofamericaPaymentStatus::Reversed
+ | BankofamericaPaymentStatus::Cancelled => Self::Voided,
BankofamericaPaymentStatus::Failed
| BankofamericaPaymentStatus::Declined
| BankofamericaPaymentStatus::AuthorizedRiskDeclined
@@ -931,9 +933,9 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus {
| BankofamericaPaymentStatus::Rejected
| BankofamericaPaymentStatus::ServerError => Self::Failure,
BankofamericaPaymentStatus::PendingAuthentication => Self::AuthenticationPending,
- BankofamericaPaymentStatus::PendingReview | BankofamericaPaymentStatus::Challenge => {
- Self::Pending
- }
+ BankofamericaPaymentStatus::PendingReview
+ | BankofamericaPaymentStatus::Challenge
+ | BankofamericaPaymentStatus::Accepted => Self::Pending,
}
}
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index fb80c0a1c48..d9fab9a9025 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1397,6 +1397,8 @@ pub enum CybersourcePaymentStatus {
ServerError,
PendingAuthentication,
PendingReview,
+ Accepted,
+ Cancelled,
//PartialAuthorized, not being consumed yet.
}
@@ -1430,7 +1432,9 @@ impl ForeignFrom<(CybersourcePaymentStatus, bool)> for enums::AttemptStatus {
CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => {
Self::Charged
}
- CybersourcePaymentStatus::Voided | CybersourcePaymentStatus::Reversed => Self::Voided,
+ CybersourcePaymentStatus::Voided
+ | CybersourcePaymentStatus::Reversed
+ | CybersourcePaymentStatus::Cancelled => Self::Voided,
CybersourcePaymentStatus::Failed
| CybersourcePaymentStatus::Declined
| CybersourcePaymentStatus::AuthorizedRiskDeclined
@@ -1438,9 +1442,9 @@ impl ForeignFrom<(CybersourcePaymentStatus, bool)> for enums::AttemptStatus {
| CybersourcePaymentStatus::InvalidRequest
| CybersourcePaymentStatus::ServerError => Self::Failure,
CybersourcePaymentStatus::PendingAuthentication => Self::AuthenticationPending,
- CybersourcePaymentStatus::PendingReview | CybersourcePaymentStatus::Challenge => {
- Self::Pending
- }
+ CybersourcePaymentStatus::PendingReview
+ | CybersourcePaymentStatus::Challenge
+ | CybersourcePaymentStatus::Accepted => Self::Pending,
}
}
}
|
2024-03-15T10:03: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 -->
The payment response will also address the `ACCEPTED` and `CANCELLED` payment status from connectors Bankofamerica and Cybersource.

### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4106
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Testing can be done by creating a recurring payment of 2USD using a Zero Auth Mandate in Cybersource.
1. Payments Intent Create:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 0,
"order_details": null,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "cut2",
"email": "johndoe@gmail.com",
"description": "Hello this is description",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
}
},
"metadata": {},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00Z",
"end_date": "2023-05-21T00:00:00Z",
"metadata": {
"frequency": "13"
}
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_4ajjiLQoHDyuxTvmS6cT",
"merchant_id": "merchant_1709635075",
"status": "requires_payment_method",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_4ajjiLQoHDyuxTvmS6cT_secret_nEJcVmz4MdM78l2X18Id",
"created": "2024-03-15T10:08:50.893Z",
"currency": "USD",
"customer_id": "cut2",
"description": "Hello this is description",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00.000Z",
"end_date": "2023-05-21T00:00:00.000Z",
"metadata": {
"frequency": "13"
}
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "johndoe@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cut2",
"created_at": 1710497330,
"expires": 1710500930,
"secret": "epk_1d6c5154433d4a3b8a3931b4f53591b8"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_dMJfhV51DYUbzCBKrQDw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T10:23:50.892Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
2. Payments Confirm:
Request:
```
curl --location 'http://localhost:8080/payments/pay_4ajjiLQoHDyuxTvmS6cT/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"off_session": true,
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "12",
"card_exp_year": "30",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8",
"language": "en-GB",
"color_depth": 24,
"screen_height": 1440,
"screen_width": 2560,
"time_zone": -330,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "0.0.0.0"
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 68607706,
"currency": "USD"
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_4ajjiLQoHDyuxTvmS6cT",
"merchant_id": "merchant_1709635075",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_4ajjiLQoHDyuxTvmS6cT_secret_nEJcVmz4MdM78l2X18Id",
"created": "2024-03-15T10:08:50.893Z",
"currency": "USD",
"customer_id": "cut2",
"description": "Hello this is description",
"refunds": null,
"disputes": null,
"mandate_id": "man_i7TaAdtRTW1qruRs87Xa",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00.000Z",
"end_date": "2023-05-21T00:00:00.000Z",
"metadata": {
"frequency": "13"
}
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "12",
"card_exp_year": "30",
"card_holder_name": "joseph Doe"
},
"billing": null
},
"payment_token": "token_flejprZEsxCiCGI8CP4a",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "johndoe@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7104973647776605504951",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_4ajjiLQoHDyuxTvmS6cT_1",
"payment_link": null,
"profile_id": "pro_dMJfhV51DYUbzCBKrQDw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T10:23:50.892Z",
"fingerprint": null,
"payment_method_id": "pm_PmD3Qlt1WtgPbdbC16ZG",
"payment_method_status": null
}
```
3. Payments Create:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 200,
"currency": "USD",
"confirm": true,
"customer_id": "cut2",
"email": "johndoe@gmail.com",
"name": "John Doe",
"phone": "999999999",
"capture_method": "automatic",
"phone_country_code": "+1",
"description": "Its my first payment request",
"return_url": "https://google.com",
"mandate_id": "man_i7TaAdtRTW1qruRs87Xa",
"off_session":true,
"browser_info": {
"ip_address":"172.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
}
}
}'
```
Response:
```
{
"payment_id": "pay_M2pKqiENVxQNMxJyOxXW",
"merchant_id": "merchant_1709635075",
"status": "processing",
"amount": 200,
"net_amount": 200,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_M2pKqiENVxQNMxJyOxXW_secret_zx26uFNfobl0m2iKU8UM",
"created": "2024-03-15T10:32:24.673Z",
"currency": "USD",
"customer_id": "cut2",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": "man_i7TaAdtRTW1qruRs87Xa",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": null,
"payment_token": "d1e9248c-579f-4322-ad12-24ba69206d24",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "johndoe@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cut2",
"created_at": 1710498744,
"expires": 1710502344,
"secret": "epk_9aab59452e7545c9a4cded4951ac4c51"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7104987458396042804953",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_M2pKqiENVxQNMxJyOxXW_1",
"payment_link": null,
"profile_id": "pro_dMJfhV51DYUbzCBKrQDw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T10:47:24.672Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
NOTE: The status should be `processing` in the above payments response.
4. Payments - Retrieve
Request:
```
curl --location 'http://localhost:8080/payments/pay_M2pKqiENVxQNMxJyOxXW?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE'
```
Response:
```
{
"payment_id": "pay_wTenpwi3b9XkyvTqyRee",
"merchant_id": "merchant_1709635075",
"status": "cancelled",
"amount": 200,
"net_amount": 200,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_wTenpwi3b9XkyvTqyRee_secret_IOIapF3mBQVf2Vj2OSan",
"created": "2024-03-15T10:48:51.707Z",
"currency": "USD",
"customer_id": "cut2",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": "man_i7TaAdtRTW1qruRs87Xa",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": null,
"payment_token": "d2d40950-39be-47d7-9741-f93e2cb89afa",
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "johndoe@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7104997332846410804953",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_wTenpwi3b9XkyvTqyRee_1",
"payment_link": null,
"profile_id": "pro_dMJfhV51DYUbzCBKrQDw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_IPBbnit5cjRQ3IpvfJ6o",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T11:03:51.707Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
NOTE: The status should be `cancelled` in the above payments retrieve response.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.