hash
stringlengths 40
40
| date
stringdate 2022-11-17 13:04:47
2025-03-21 17:04:41
| author
stringclasses 141
values | commit_message
stringlengths 22
166
| is_merge
bool 1
class | git_diff
stringlengths 238
9.63M
| type
stringclasses 17
values | masked_commit_message
stringlengths 6
143
|
|---|---|---|---|---|---|---|---|
afae5906a8d6ceab136393c7588bfc447e822ddc
|
2024-07-23 20:54:56
|
Sakil Mostak
|
refactor(connector): [Itaubank] add dynamic fields for pix (#5419)
| false
|
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index e55485e945a..03dbf539c3b 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -9847,6 +9847,24 @@
}
}
}
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_pix_key"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_cpf"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_cnpj"
+ ]
}
],
"description": "Possible field type of required fields in payment_method_data"
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 79cb60da2d7..85212ec7d0c 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -476,6 +476,9 @@ pub enum FieldType {
UserDateOfBirth,
UserVpaId,
LanguagePreference { options: Vec<String> },
+ UserPixKey,
+ UserCpf,
+ UserCnpj,
}
impl FieldType {
@@ -562,6 +565,9 @@ impl PartialEq for FieldType {
) => options_self.eq(options_other),
(Self::UserDateOfBirth, Self::UserDateOfBirth) => true,
(Self::UserVpaId, Self::UserVpaId) => true,
+ (Self::UserPixKey, Self::UserPixKey) => true,
+ (Self::UserCpf, Self::UserCpf) => true,
+ (Self::UserCnpj, Self::UserCnpj) => true,
(Self::LanguagePreference { .. }, Self::LanguagePreference { .. }) => true,
_unused => false,
}
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 6121d8e503f..ffa3d81edea 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -8871,7 +8871,49 @@ impl Default for super::settings::RequiredFields {
}
),
])}),
- ])))
+ (enums::PaymentMethodType::Pix,
+ ConnectorFields {
+ fields: HashMap::from([
+ (
+ enums::Connector::Itaubank,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from(
+ [
+ (
+ "payment_method_data.bank_transfer.pix.pix_key".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.bank_transfer.pix.pix_key".to_string(),
+ display_name: "pix_key".to_string(),
+ field_type: enums::FieldType::UserPixKey,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.bank_transfer.pix.cnpj".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.bank_transfer.pix.cnpj".to_string(),
+ display_name: "cnpj".to_string(),
+ field_type: enums::FieldType::UserCnpj,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.bank_transfer.pix.cpf".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.bank_transfer.pix.cpf".to_string(),
+ display_name: "cpf".to_string(),
+ field_type: enums::FieldType::UserCpf,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ }
+ ),
+ ])}),
+ ])))
]))
}
}
|
refactor
|
[Itaubank] add dynamic fields for pix (#5419)
|
ea6bce663dcb084b5990834cb922eec5c626e897
|
2023-05-23 16:11:45
|
Sangamesh Kulkarni
|
test(connector): [Stripe] Fix redirection UI tests (#1215)
| false
|
diff --git a/crates/router/tests/connectors/stripe_ui.rs b/crates/router/tests/connectors/stripe_ui.rs
index f50d6670155..019979d1aee 100644
--- a/crates/router/tests/connectors/stripe_ui.rs
+++ b/crates/router/tests/connectors/stripe_ui.rs
@@ -23,7 +23,7 @@ async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
async fn should_make_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
- Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_DREFLPJC5SFpFBupKYovdCfg37xgM20g7oXVLQMHXP3t2kJMRSy6aof1rTe6tyyK&return_url={CHEKOUT_BASE_URL}/payments"))),
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHEKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
@@ -42,7 +42,7 @@ async fn should_fail_recurring_payment_due_to_authentication(
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
- Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002760003184&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_DREFLPJC5SFpFBupKYovdCfg37xgM20g7oXVLQMHXP3t2kJMRSy6aof1rTe6tyyK&return_url={CHEKOUT_BASE_URL}/payments"))),
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002760003184&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHEKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
@@ -61,7 +61,7 @@ async fn should_make_3ds_mandate_with_zero_dollar_payment(
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
- Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=0&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&apikey=dev_DREFLPJC5SFpFBupKYovdCfg37xgM20g7oXVLQMHXP3t2kJMRSy6aof1rTe6tyyK&return_url={CHEKOUT_BASE_URL}/payments"))),
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=0&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHEKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
|
test
|
[Stripe] Fix redirection UI tests (#1215)
|
0a03d69b1627893b09688d833f86c5e54a76ae37
|
2023-08-04 13:28:37
|
Sanchith Hegde
|
ci: use `sccache-action` for caching compilation artifacts (#1857)
| false
|
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml
index 61d4c6f7df5..a13f0eb51e0 100644
--- a/.github/workflows/CI-pr.yml
+++ b/.github/workflows/CI-pr.yml
@@ -35,6 +35,9 @@ env:
RUST_BACKTRACE: short
# Use cargo's sparse index protocol
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
+ # Enable and use the sccache action for caching
+ SCCACHE_GHA_ENABLED: "true"
+ RUSTC_WRAPPER: "sccache"
jobs:
formatting:
@@ -84,9 +87,7 @@ jobs:
with:
toolchain: 1.65
- - uses: Swatinem/[email protected]
- with:
- save-if: ${{ github.event_name == 'push' }}
+ - uses: mozilla-actions/[email protected]
- name: Install cargo-hack
uses: baptiste0928/[email protected]
@@ -293,9 +294,7 @@ jobs:
# with:
# crate: cargo-nextest
- - uses: Swatinem/[email protected]
- with:
- save-if: ${{ github.event_name == 'push' }}
+ - uses: mozilla-actions/[email protected]
# - name: Setup Embark Studios lint rules
# shell: bash
diff --git a/.github/workflows/CI-push.yml b/.github/workflows/CI-push.yml
index e087c694c54..cba1fb715d4 100644
--- a/.github/workflows/CI-push.yml
+++ b/.github/workflows/CI-push.yml
@@ -19,6 +19,32 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
+env:
+ # Disable incremental compilation.
+ #
+ # Incremental compilation is useful as part of an edit-build-test-edit cycle,
+ # as it lets the compiler avoid recompiling code that hasn't changed. However,
+ # on CI, we're not making small edits; we're almost always building the entire
+ # project from scratch. Thus, incremental compilation on CI actually
+ # introduces *additional* overhead to support making future builds
+ # faster...but no future builds will ever occur in any given CI environment.
+ #
+ # See https://matklad.github.io/2021/09/04/fast-rust-builds.html#ci-workflow
+ # for details.
+ CARGO_INCREMENTAL: 0
+ # Allow more retries for network requests in cargo (downloading crates) and
+ # rustup (installing toolchains). This should help to reduce flaky CI failures
+ # from transient network timeouts or other issues.
+ CARGO_NET_RETRY: 10
+ RUSTUP_MAX_RETRIES: 10
+ # Don't emit giant backtraces in the CI logs.
+ RUST_BACKTRACE: short
+ # Use cargo's sparse index protocol
+ CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
+ # Enable and use the sccache action for caching
+ SCCACHE_GHA_ENABLED: "true"
+ RUSTC_WRAPPER: "sccache"
+
jobs:
formatting:
name: Check formatting
@@ -63,9 +89,7 @@ jobs:
with:
toolchain: 1.65
- - uses: Swatinem/[email protected]
- with:
- save-if: ${{ github.event_name == 'push' }}
+ - uses: mozilla-actions/[email protected]
- name: Install cargo-hack
uses: baptiste0928/[email protected]
@@ -138,9 +162,7 @@ jobs:
# with:
# crate: cargo-nextest
- - uses: Swatinem/[email protected]
- with:
- save-if: ${{ github.event_name == 'push' }}
+ - uses: mozilla-actions/[email protected]
# - name: Setup Embark Studios lint rules
# shell: bash
diff --git a/.github/workflows/connector-sanity-tests.yml b/.github/workflows/connector-sanity-tests.yml
index 4d6199a86d3..1aa14e56435 100644
--- a/.github/workflows/connector-sanity-tests.yml
+++ b/.github/workflows/connector-sanity-tests.yml
@@ -38,6 +38,9 @@ env:
RUST_BACKTRACE: short
# Use cargo's sparse index protocol
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
+ # Enable and use the sccache action for caching
+ SCCACHE_GHA_ENABLED: "true"
+ RUSTC_WRAPPER: "sccache"
jobs:
test_connectors:
@@ -86,7 +89,7 @@ jobs:
with:
toolchain: stable
- - uses: Swatinem/[email protected]
+ - uses: mozilla-actions/[email protected]
- name: Decrypt connector auth file
env:
diff --git a/.github/workflows/connector-ui-sanity-tests.yml b/.github/workflows/connector-ui-sanity-tests.yml
index 9c81d715b19..4809451d51e 100644
--- a/.github/workflows/connector-ui-sanity-tests.yml
+++ b/.github/workflows/connector-ui-sanity-tests.yml
@@ -2,9 +2,9 @@ name: Connector UI Sanity Tests
on:
workflow_dispatch:
-
+
pull_request_review:
- types:
+ types:
- submitted
merge_group:
types:
@@ -26,7 +26,7 @@ env:
#
# See https://matklad.github.io/2021/09/04/fast-rust-builds.html#ci-workflow
# for details.
- CARGO_INCREMENTAL: 1
+ CARGO_INCREMENTAL: 0
# Allow more retries for network requests in cargo (downloading crates) and
# rustup (installing toolchains). This should help to reduce flaky CI failures
# from transient network timeouts or other issues.
@@ -36,6 +36,9 @@ env:
RUST_BACKTRACE: short
# Use cargo's sparse index protocol
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
+ # Enable and use the sccache action for caching
+ SCCACHE_GHA_ENABLED: "true"
+ RUSTC_WRAPPER: "sccache"
jobs:
test_connectors:
@@ -73,14 +76,13 @@ jobs:
# do not use more than 2 runners, try to group less time taking connectors together
- stripe,airwallex,bluesnap,checkout,trustpay_3ds,payu,authorizedotnet,aci,noon
- adyen_uk,shift4,worldline,multisafepay,paypal,mollie,nexinets
-
steps:
- name: Ignore Tests incase of pull request
if: github.event_name == 'pull_request' || github.event_name == 'merge_group'
shell: bash
run: |
- echo "Skipped tests as the event is pull request"
+ echo "Skipped tests as the event is pull request"
exit 0
- name: Checkout repository
@@ -105,34 +107,34 @@ jobs:
run: echo "CONNECTOR_TESTS_FILE_PATH=$HOME/target/test/connector_tests.json" >> $GITHUB_ENV
- name: Set ignore_browser_profile usage in env
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
shell: bash
run: echo "IGNORE_BROWSER_PROFILE=true" >> $GITHUB_ENV
- name: Install latest compiler
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- - uses: Swatinem/[email protected]
+ - uses: mozilla-actions/[email protected]
- uses: baptiste0928/[email protected]
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
with:
crate: diesel_cli
features: postgres
args: "--no-default-features"
- name: Diesel migration run
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
shell: bash
env:
DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
run: diesel migration run
- name: Start server and run tests
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
env:
UI_TESTCASES_PATH: ${{ secrets.UI_TESTCASES_PATH }}
INPUT: ${{ matrix.connector }}
@@ -140,12 +142,12 @@ jobs:
run: sh .github/scripts/run_ui_tests.sh
- name: View test results
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
shell: bash
run: cat tests/test_results.log
- name: Check test results
- if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
+ if: (github.event_name == 'pull_request_review' && github.event.review.state == 'approved') || (github.event_name == 'workflow_dispatch')
shell: bash
run: |
if test "$( grep 'test result: FAILED' -r tests/test_results.log | wc -l )" -gt "0"; then
diff --git a/.github/workflows/postman-collection-runner.yml b/.github/workflows/postman-collection-runner.yml
index 37c1bdd1b31..b7615524c31 100644
--- a/.github/workflows/postman-collection-runner.yml
+++ b/.github/workflows/postman-collection-runner.yml
@@ -16,7 +16,9 @@ env:
RUSTUP_MAX_RETRIES: 10
RUST_BACKTRACE: short
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
- CONNECTORS: aci, adyen_uk, airwallex, authorizedotnet, bambora, bambora_3ds, bluesnap, checkout, globalpay, mollie, nexinets, nmi, shift4, stripe, trustpay, worldline
+ CONNECTORS: "aci, adyen_uk, airwallex, authorizedotnet, bambora, bambora_3ds, bluesnap, checkout, globalpay, mollie, nexinets, nmi, shift4, stripe, trustpay, worldline"
+ SCCACHE_GHA_ENABLED: "true"
+ RUSTC_WRAPPER: "sccache"
jobs:
runner:
@@ -33,6 +35,7 @@ jobs:
--health-retries 5
ports:
- 6379:6379
+
postgres:
image: "${{ github.event_name != 'pull_request' && 'postgres:14.5' || '' }}"
env:
@@ -52,7 +55,7 @@ jobs:
if: github.event_name == 'pull_request'
shell: bash
run: |
- echo "Skipped tests as the event is pull request"
+ echo "Skipped tests as the event is pull request"
exit 0
- name: Repository checkout
@@ -87,9 +90,8 @@ jobs:
with:
toolchain: stable
- - name: Build and Cache Rust Dependencies
+ - uses: mozilla-actions/[email protected]
if: github.event_name != 'pull_request'
- uses: Swatinem/[email protected]
- name: Install Diesel CLI with Postgres Support
if: github.event_name != 'pull_request'
@@ -112,12 +114,12 @@ jobs:
cargo run &
COUNT=0
# Wait for the server to start in port 8080
- while netstat -lnt | awk '$4 ~ /:8080$/ {exit 1}'; do
+ while netstat -lnt | awk '$4 ~ /:8080$/ {exit 1}'; do
# Wait for 15 mins to start otherwise kill the task
if [ $COUNT -gt 90 ];
then
exit 1
- else
+ else
COUNT=$((COUNT+1))
sleep 10
fi
diff --git a/.github/workflows/validate-openapi-spec.yml b/.github/workflows/validate-openapi-spec.yml
index 72b76157f10..a25380ffad7 100644
--- a/.github/workflows/validate-openapi-spec.yml
+++ b/.github/workflows/validate-openapi-spec.yml
@@ -11,6 +11,32 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
+env:
+ # Disable incremental compilation.
+ #
+ # Incremental compilation is useful as part of an edit-build-test-edit cycle,
+ # as it lets the compiler avoid recompiling code that hasn't changed. However,
+ # on CI, we're not making small edits; we're almost always building the entire
+ # project from scratch. Thus, incremental compilation on CI actually
+ # introduces *additional* overhead to support making future builds
+ # faster...but no future builds will ever occur in any given CI environment.
+ #
+ # See https://matklad.github.io/2021/09/04/fast-rust-builds.html#ci-workflow
+ # for details.
+ CARGO_INCREMENTAL: 0
+ # Allow more retries for network requests in cargo (downloading crates) and
+ # rustup (installing toolchains). This should help to reduce flaky CI failures
+ # from transient network timeouts or other issues.
+ CARGO_NET_RETRY: 10
+ RUSTUP_MAX_RETRIES: 10
+ # Don't emit giant backtraces in the CI logs.
+ RUST_BACKTRACE: short
+ # Use cargo's sparse index protocol
+ CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
+ # Enable and use the sccache action for caching
+ SCCACHE_GHA_ENABLED: "true"
+ RUSTC_WRAPPER: "sccache"
+
jobs:
validate_json:
name: Validate generated OpenAPI spec file
@@ -35,6 +61,8 @@ jobs:
with:
toolchain: stable
+ - uses: mozilla-actions/[email protected]
+
- name: Generate the OpenAPI spec file
shell: bash
run: cargo run --features openapi -- generate-openapi-spec
|
ci
|
use `sccache-action` for caching compilation artifacts (#1857)
|
740749e18ae4458726cdf2501f3d3b789c819f7a
|
2024-04-01 18:49:55
|
Hrithikesh
|
feat: return customer details in payments response body (#4237)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 72592ec3cad..63b29306113 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -169,7 +169,7 @@ mod client_secret_tests {
}
}
-#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)]
pub struct CustomerDetails {
/// The identifier for the customer.
pub id: String,
@@ -2935,6 +2935,9 @@ pub struct PaymentsResponse {
#[schema(max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<String>,
+ /// Details of customer attached to this payment
+ pub customer: Option<CustomerDetails>,
+
/// A description of the payment
#[schema(example = "It's my first payment request")]
pub description: Option<String>,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index d686d741c88..9aa552b86d8 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -490,6 +490,8 @@ where
))
}
+ let customer_details_response = customer.as_ref().map(ForeignInto::foreign_into);
+
headers.extend(
external_latency
.map(|latency| {
@@ -779,6 +781,7 @@ where
.set_payment_method_status(
payment_data.payment_method_info.map(|info| info.status),
)
+ .set_customer(customer_details_response.clone())
.to_owned(),
headers,
))
@@ -849,6 +852,7 @@ where
expires_on: payment_intent.session_expiry,
external_3ds_authentication_attempted: payment_attempt
.external_three_ds_authentication_attempted,
+ customer: customer_details_response,
..Default::default()
},
headers,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 8a53a58aabd..237dea196d6 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1130,6 +1130,24 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse {
}
}
+impl ForeignFrom<&domain::Customer> for api_models::payments::CustomerDetails {
+ fn foreign_from(customer: &domain::Customer) -> Self {
+ Self {
+ id: customer.customer_id.clone(),
+ name: customer
+ .name
+ .as_ref()
+ .map(|name| name.get_inner().to_owned()),
+ email: customer.email.clone().map(Into::into),
+ phone: customer
+ .phone
+ .as_ref()
+ .map(|phone| phone.get_inner().to_owned()),
+ phone_country_code: customer.phone_country_code.clone(),
+ }
+ }
+}
+
#[cfg(feature = "olap")]
impl ForeignTryFrom<api_types::webhook_events::EventListConstraints>
for api_types::webhook_events::EventListConstraintsInternal
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index fa9c7435632..1e16d072471 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -14338,6 +14338,14 @@
"nullable": true,
"maxLength": 255
},
+ "customer": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDetails"
+ }
+ ],
+ "nullable": true
+ },
"description": {
"type": "string",
"description": "A description of the payment",
|
feat
|
return customer details in payments response body (#4237)
|
fe3cf54781302c733c1682ded2c1735544407a5f
|
2024-01-10 16:57:53
|
Branislav Kontur
|
chore: nits and small code improvements found during investigation of PR#3168 (#3259)
| false
|
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 886de4174db..39b404d0f55 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -806,7 +806,7 @@ impl CardData for api::Card {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
- self.card_exp_month.peek().clone(),
+ self.card_exp_month.peek(),
delimiter,
year.peek()
)))
@@ -817,14 +817,14 @@ impl CardData for api::Card {
"{}{}{}",
year.peek(),
delimiter,
- self.card_exp_month.peek().clone()
+ self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
- self.card_exp_month.peek().clone(),
+ self.card_exp_month.peek(),
delimiter,
year.peek()
))
@@ -1211,7 +1211,7 @@ where
{
let connector_meta_secret =
connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
- let json = connector_meta_secret.peek().clone();
+ let json = connector_meta_secret.expose();
json.parse_value(std::any::type_name::<T>()).switch()
}
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index c00913aa57d..c55663d59f4 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -342,7 +342,7 @@ fn make_card_request(
req: &PaymentsAuthorizeData,
ccard: &payments::Card,
) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> {
- let expiry_year = ccard.card_exp_year.peek().clone();
+ let expiry_year = ccard.card_exp_year.peek();
let secret_value = format!(
"{}{}",
ccard.card_exp_month.peek(),
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 8be1876aed5..ad3a7638774 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -2,7 +2,7 @@ use std::fmt::Debug;
use api_models::{admin::FrmConfigs, enums as api_enums, payments::AdditionalPaymentData};
use error_stack::ResultExt;
-use masking::PeekInterface;
+use masking::{ExposeInterface, PeekInterface};
use router_env::{
logger,
tracing::{self, instrument},
@@ -167,10 +167,9 @@ where
match frm_configs_option {
Some(frm_configs_value) => {
let frm_configs_struct: Vec<FrmConfigs> = frm_configs_value
- .iter()
+ .into_iter()
.map(|config| { config
- .peek()
- .clone()
+ .expose()
.parse_value("FrmConfigs")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index c25b0241581..070bca234c8 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -47,7 +47,7 @@ impl Vaultable for api::Card {
exp_month: self.card_exp_month.peek().clone(),
name_on_card: self
.card_holder_name
- .clone()
+ .as_ref()
.map(|name| name.peek().clone()),
nickname: None,
card_last_four: None,
|
chore
|
nits and small code improvements found during investigation of PR#3168 (#3259)
|
70b86b71e4809d2a47c6bc1214f72c37d3325c37
|
2023-12-14 16:45:10
|
Sampras Lopes
|
fix(locker): fix double serialization for json request (#3134)
| false
|
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 71c2cf8f200..5506dc7eb9a 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -313,9 +313,6 @@ pub async fn mk_add_locker_request_hs<'a>(
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload = mk_basilisk_req(jwekey, &jws, locker_choice).await?;
-
- let body = utils::Encode::<encryption::JweBody>::encode_to_value(&jwe_payload)
- .change_context(errors::VaultError::RequestEncodingFailed)?;
let mut url = match locker_choice {
api_enums::LockerChoice::Basilisk => locker.host.to_owned(),
api_enums::LockerChoice::Tartarus => locker.host_rs.to_owned(),
@@ -323,7 +320,7 @@ pub async fn mk_add_locker_request_hs<'a>(
url.push_str("/cards/add");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
- request.set_body(RequestContent::Json(Box::new(body.to_string())));
+ request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -459,9 +456,6 @@ pub async fn mk_get_card_request_hs(
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::Basilisk);
let jwe_payload = mk_basilisk_req(jwekey, &jws, target_locker).await?;
-
- let body = utils::Encode::<encryption::JweBody>::encode_to_value(&jwe_payload)
- .change_context(errors::VaultError::RequestEncodingFailed)?;
let mut url = match target_locker {
api_enums::LockerChoice::Basilisk => locker.host.to_owned(),
api_enums::LockerChoice::Tartarus => locker.host_rs.to_owned(),
@@ -469,7 +463,7 @@ pub async fn mk_get_card_request_hs(
url.push_str("/cards/retrieve");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
- request.set_body(RequestContent::Json(Box::new(body.to_string())));
+ request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -537,13 +531,11 @@ pub async fn mk_delete_card_request_hs(
let jwe_payload = mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::Basilisk).await?;
- let body = utils::Encode::<encryption::JweBody>::encode_to_value(&jwe_payload)
- .change_context(errors::VaultError::RequestEncodingFailed)?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
- request.set_body(RequestContent::Json(Box::new(body.to_string())));
+ request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -602,14 +594,12 @@ pub fn mk_crud_locker_request(
path: &str,
req: api::TokenizePayloadEncrypted,
) -> CustomResult<services::Request, errors::VaultError> {
- let body = utils::Encode::<api::TokenizePayloadEncrypted>::encode_to_value(&req)
- .change_context(errors::VaultError::RequestEncodingFailed)?;
let mut url = locker.basilisk_host.to_owned();
url.push_str(path);
let mut request = services::Request::new(services::Method::Post, &url);
request.add_default_headers();
request.add_header(headers::CONTENT_TYPE, "application/json".into());
- request.set_body(RequestContent::Json(Box::new(body.to_string())));
+ request.set_body(RequestContent::Json(Box::new(req)));
Ok(request)
}
|
fix
|
fix double serialization for json request (#3134)
|
c8d35449cfe6113f184a972100bfc1cdeab9b662
|
2023-09-25 20:03:33
|
github-actions
|
chore(version): v1.46.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 275e35aeb32..eb54ed9a85f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,33 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.46.0 (2023-09-25)
+
+### Features
+
+- **payment_attempt:** Add kv for find last successful attempt ([#2206](https://github.com/juspay/hyperswitch/pull/2206)) ([`d3157f0`](https://github.com/juspay/hyperswitch/commit/d3157f0bd6a0246c28182c88335d95ed6ae298a9))
+- **payments:** Add api locking for payments core ([#1898](https://github.com/juspay/hyperswitch/pull/1898)) ([`5d66156`](https://github.com/juspay/hyperswitch/commit/5d661561322a21f792e2cdb2ae8c30de96ce7d02))
+
+### Bug Fixes
+
+- **compatibility:** Update BillingDetails mappings in SCL ([#1926](https://github.com/juspay/hyperswitch/pull/1926)) ([`a48f986`](https://github.com/juspay/hyperswitch/commit/a48f9865bcd29d5c3fc5c380dde34b11c6bb254f))
+- **connector:** [stripe] use display impl for expiry date ([#2359](https://github.com/juspay/hyperswitch/pull/2359)) ([`35622af`](https://github.com/juspay/hyperswitch/commit/35622aff7a042764729565db1ed5aca2257603ba))
+- **drainer:** Ignore errors in case the stream is empty ([#2261](https://github.com/juspay/hyperswitch/pull/2261)) ([`53de86f`](https://github.com/juspay/hyperswitch/commit/53de86f60d14981087626e1a2a5856089b6f3899))
+- Add health metric to drainer ([#2217](https://github.com/juspay/hyperswitch/pull/2217)) ([`4e8471b`](https://github.com/juspay/hyperswitch/commit/4e8471be501806ceeb96c7683be00600c3c1a0d2))
+
+### Refactors
+
+- Enable `logs` feature flag in router crate ([#2358](https://github.com/juspay/hyperswitch/pull/2358)) ([`e4af381`](https://github.com/juspay/hyperswitch/commit/e4af3812d55689aefb5bb8ed6f12a6c9c0643a51))
+
+### Testing
+
+- **postman:** Update postman collection files ([`d7affab`](https://github.com/juspay/hyperswitch/commit/d7affab455adf1eeccaca3005797a81e51c902ac))
+
+**Full Changelog:** [`v1.45.0...v1.46.0`](https://github.com/juspay/hyperswitch/compare/v1.45.0...v1.46.0)
+
+- - -
+
+
## 1.45.0 (2023-09-22)
### Features
|
chore
|
v1.46.0
|
8a9fed36fc7f01f54d9a2e725abf459fac857222
|
2024-09-24 05:54:48
|
github-actions
|
chore(version): 2024.09.24.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46ac76cf7ae..c3e2bd01a15 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,21 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.09.24.0
+
+### Features
+
+- **refunds:** Profile level refunds aggregate ([#5931](https://github.com/juspay/hyperswitch/pull/5931)) ([`f5e6165`](https://github.com/juspay/hyperswitch/commit/f5e61659d10c6670df80e4ff8e3e0a5fd3b7ec6b))
+
+### Bug Fixes
+
+- **payment_link:** Payment link render issue when `transaction_details` not passed ([#5948](https://github.com/juspay/hyperswitch/pull/5948)) ([`035906e`](https://github.com/juspay/hyperswitch/commit/035906e9b1b1a1e52fe970db5d7e028556fa82b4))
+- Log detailed error reports during deep health check failures ([#5984](https://github.com/juspay/hyperswitch/pull/5984)) ([`19e52b4`](https://github.com/juspay/hyperswitch/commit/19e52b420002c681a5a7312e6330e6f4726809f5))
+
+**Full Changelog:** [`2024.09.23.0...2024.09.24.0`](https://github.com/juspay/hyperswitch/compare/2024.09.23.0...2024.09.24.0)
+
+- - -
+
## 2024.09.23.0
### Features
|
chore
|
2024.09.24.0
|
4ce86afd4e00a036eba9b70916b4880a049e4d9f
|
2022-11-23 20:58:07
|
Narayan Bhat
|
feat(core): add server base_url in server config (#12)
| false
|
diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml
index 75de8516d92..6cb55040318 100644
--- a/crates/router/src/configs/defaults.toml
+++ b/crates/router/src/configs/defaults.toml
@@ -4,6 +4,7 @@
port = 8080
host = "127.0.0.1"
request_body_limit = 16_384 # Post request body is limited to 16k.
+base_url = "http://localhost:8080"
[proxy]
# http_url = ""
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 07fb6a41a47..d4dfbfb360c 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -62,6 +62,7 @@ pub struct Server {
pub port: u16,
pub host: String,
pub request_body_limit: usize,
+ pub base_url: String,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 1b1f682c48b..294b10da5af 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -291,32 +291,24 @@ fn validate_new_mandate_request(req: &api::PaymentsRequest) -> RouterResult<()>
Ok(())
}
-pub fn create_server_url(server: &Server) -> String {
- if server.host.eq("127.0.0.1") || server.host.eq("localhost") {
- format!("http://{}:{}", server.host, server.port)
- } else {
- format!("https://{}", server.host)
- }
-}
pub fn create_startpay_url(
server: &Server,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
) -> String {
- let server_url = create_server_url(server);
-
format!(
"{}/payments/start/{}/{}/{}",
- server_url, payment_intent.payment_id, payment_intent.merchant_id, payment_attempt.txn_id
+ server.base_url,
+ payment_intent.payment_id,
+ payment_intent.merchant_id,
+ payment_attempt.txn_id
)
}
pub fn create_redirect_url(server: &Server, payment_attempt: &storage::PaymentAttempt) -> String {
- let server_url = create_server_url(server);
-
format!(
"{}/payments/{}/{}/response/{}",
- server_url,
+ server.base_url,
payment_attempt.payment_id,
payment_attempt.merchant_id,
payment_attempt.connector
|
feat
|
add server base_url in server config (#12)
|
39d2d6c43800f609070b61a6148ddef7e40001bc
|
2025-01-21 17:14:14
|
Sarthak Soni
|
feat(routing): Integrate global success rates (#6950)
| false
|
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index b282566e509..d218e4d2074 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -25202,9 +25202,19 @@
}
],
"nullable": true
+ },
+ "specificity_level": {
+ "$ref": "#/components/schemas/SuccessRateSpecificityLevel"
}
}
},
+ "SuccessRateSpecificityLevel": {
+ "type": "string",
+ "enum": [
+ "merchant",
+ "global"
+ ]
+ },
"SupportedPaymentMethod": {
"allOf": [
{
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 2e570816ab4..8e502767575 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -779,6 +779,7 @@ impl Default for SuccessBasedRoutingConfig {
duration_in_mins: Some(5),
max_total_count: Some(2),
}),
+ specificity_level: SuccessRateSpecificityLevel::default(),
}),
}
}
@@ -801,6 +802,8 @@ pub struct SuccessBasedRoutingConfigBody {
pub default_success_rate: Option<f64>,
pub max_aggregates_size: Option<u32>,
pub current_block_threshold: Option<CurrentBlockThreshold>,
+ #[serde(default)]
+ pub specificity_level: SuccessRateSpecificityLevel,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
@@ -809,6 +812,14 @@ pub struct CurrentBlockThreshold {
pub max_total_count: Option<u64>,
}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum SuccessRateSpecificityLevel {
+ #[default]
+ Merchant,
+ Global,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuccessBasedRoutingPayloadWrapper {
pub updated_config: SuccessBasedRoutingConfig,
@@ -849,6 +860,7 @@ impl SuccessBasedRoutingConfigBody {
.as_mut()
.map(|threshold| threshold.update(current_block_threshold));
}
+ self.specificity_level = new.specificity_level
}
}
diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs
index c055359d8b0..90cf4689080 100644
--- a/crates/diesel_models/src/dynamic_routing_stats.rs
+++ b/crates/diesel_models/src/dynamic_routing_stats.rs
@@ -20,6 +20,7 @@ pub struct DynamicRoutingStatsNew {
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub created_at: time::PrimitiveDateTime,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub global_success_based_connector: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)]
@@ -40,4 +41,5 @@ pub struct DynamicRoutingStats {
pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
pub created_at: time::PrimitiveDateTime,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub global_success_based_connector: Option<String>,
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index dfe3d5acc23..7930ad5d9ae 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -435,6 +435,8 @@ diesel::table! {
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
+ #[max_length = 64]
+ global_success_based_connector -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index b5361f4c95c..13abf8ee64b 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -447,6 +447,8 @@ diesel::table! {
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
+ #[max_length = 64]
+ global_success_based_connector -> Nullable<Varchar>,
}
}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
index fca4ff61fcc..278a2b50d15 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
@@ -1,15 +1,17 @@
use api_models::routing::{
CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
- SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,
+ SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, SuccessRateSpecificityLevel,
};
use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
pub use success_rate::{
- success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
+ success_rate_calculator_client::SuccessRateCalculatorClient, CalGlobalSuccessRateConfig,
+ CalGlobalSuccessRateRequest, CalGlobalSuccessRateResponse, CalSuccessRateConfig,
CalSuccessRateRequest, CalSuccessRateResponse,
CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
- InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig,
+ InvalidateWindowsResponse, LabelWithStatus,
+ SuccessRateSpecificityLevel as ProtoSpecificityLevel, UpdateSuccessRateWindowConfig,
UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
#[allow(
@@ -51,6 +53,15 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse>;
+ /// To calculate both global and merchant specific success rate for the list of chosen connectors
+ async fn calculate_entity_and_global_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
+ label_input: Vec<RoutableConnectorChoice>,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<CalGlobalSuccessRateResponse>;
}
#[async_trait::async_trait]
@@ -113,6 +124,7 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
.transpose()?;
let labels_with_status = label_input
+ .clone()
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.to_string(),
@@ -120,12 +132,21 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
})
.collect();
+ let global_labels_with_status = label_input
+ .into_iter()
+ .map(|conn_choice| LabelWithStatus {
+ label: conn_choice.routable_connector_choice.connector.to_string(),
+ status: conn_choice.status,
+ })
+ .collect();
+
let request = grpc_client::create_grpc_request(
UpdateSuccessRateWindowRequest {
id,
params,
labels_with_status,
config,
+ global_labels_with_status,
},
headers,
);
@@ -165,6 +186,55 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
Ok(response)
}
+
+ async fn calculate_entity_and_global_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
+ label_input: Vec<RoutableConnectorChoice>,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<CalGlobalSuccessRateResponse> {
+ let labels = label_input
+ .clone()
+ .into_iter()
+ .map(|conn_choice| conn_choice.to_string())
+ .collect::<Vec<_>>();
+
+ let global_labels = label_input
+ .into_iter()
+ .map(|conn_choice| conn_choice.connector.to_string())
+ .collect::<Vec<_>>();
+
+ let config = success_rate_based_config
+ .config
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?;
+
+ let request = grpc_client::create_grpc_request(
+ CalGlobalSuccessRateRequest {
+ entity_id: id,
+ entity_params: params,
+ entity_labels: labels,
+ global_labels,
+ config,
+ },
+ headers,
+ );
+
+ let response = self
+ .clone()
+ .fetch_entity_and_global_success_rate(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to fetch the entity and global success rate".to_string(),
+ ))?
+ .into_inner();
+
+ logger::info!(dynamic_routing_response=?response);
+
+ Ok(response)
+ }
}
impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
@@ -216,6 +286,30 @@ impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig {
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
+ specificity_level: match config.specificity_level {
+ SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()),
+ SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()),
+ },
+ })
+ }
+}
+
+impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalGlobalSuccessRateConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
+ Ok(Self {
+ entity_min_aggregates_size: config
+ .min_aggregates_size
+ .get_required_value("min_aggregate_size")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "min_aggregates_size".to_string(),
+ })?,
+ entity_default_success_rate: config
+ .default_success_rate
+ .get_required_value("default_success_rate")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "default_success_rate".to_string(),
+ })?,
})
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index f3068e1b50b..3a634ae2a54 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -624,6 +624,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
+ api_models::routing::SuccessRateSpecificityLevel,
api_models::routing::ToggleDynamicRoutingQuery,
api_models::routing::ToggleDynamicRoutingPath,
api_models::routing::ast::RoutableChoiceKind,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 1395563a30a..ca14e3e7e48 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -714,7 +714,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
);
let success_based_connectors = client
- .calculate_success_rate(
+ .calculate_entity_and_global_success_rate(
business_profile.get_id().get_string_repr().into(),
success_based_routing_configs.clone(),
success_based_routing_config_params.clone(),
@@ -730,28 +730,34 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
let payment_status_attribute =
get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);
- let first_success_based_connector_label = &success_based_connectors
- .labels_with_score
+ let first_merchant_success_based_connector = &success_based_connectors
+ .entity_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
- )?
- .label
- .to_string();
+ )?;
- let (first_success_based_connector, _) = first_success_based_connector_label
+ let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
- first_success_based_connector_label
+ first_merchant_success_based_connector.label
))?;
+ let first_global_success_based_connector = &success_based_connectors
+ .global_scores_with_labels
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
+ )?;
+
let outcome = get_success_based_metrics_outcome_for_payment(
payment_status_attribute,
payment_connector.to_string(),
- first_success_based_connector.to_string(),
+ first_merchant_success_based_connector_label.to_string(),
);
let dynamic_routing_stats = DynamicRoutingStatsNew {
@@ -760,7 +766,8 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
merchant_id: payment_attempt.merchant_id.to_owned(),
profile_id: payment_attempt.profile_id.to_owned(),
amount: payment_attempt.get_total_amount(),
- success_based_routing_connector: first_success_based_connector.to_string(),
+ success_based_routing_connector: first_merchant_success_based_connector_label
+ .to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
@@ -770,6 +777,9 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
payment_status: payment_attempt.status,
conclusive_classification: outcome,
created_at: common_utils::date_time::now(),
+ global_success_based_connector: Some(
+ first_global_success_based_connector.label.to_string(),
+ ),
};
core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
@@ -788,8 +798,20 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
),
),
(
- "success_based_routing_connector",
- first_success_based_connector.to_string(),
+ "merchant_specific_success_based_routing_connector",
+ first_merchant_success_based_connector_label.to_string(),
+ ),
+ (
+ "merchant_specific_success_based_routing_connector_score",
+ first_merchant_success_based_connector.score.to_string(),
+ ),
+ (
+ "global_success_based_routing_connector",
+ first_global_success_based_connector.label.to_string(),
+ ),
+ (
+ "global_success_based_routing_connector_score",
+ first_global_success_based_connector.score.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
diff --git a/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql
new file mode 100644
index 00000000000..c99db9a384d
--- /dev/null
+++ b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE dynamic_routing_stats
+DROP COLUMN IF EXISTS global_success_based_connector;
\ No newline at end of file
diff --git a/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql
new file mode 100644
index 00000000000..81e00a9753c
--- /dev/null
+++ b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE dynamic_routing_stats
+ADD COLUMN IF NOT EXISTS global_success_based_connector VARCHAR(64);
\ No newline at end of file
diff --git a/proto/success_rate.proto b/proto/success_rate.proto
index f49618bc4b6..17d566af356 100644
--- a/proto/success_rate.proto
+++ b/proto/success_rate.proto
@@ -7,6 +7,8 @@ service SuccessRateCalculator {
rpc UpdateSuccessRateWindow (UpdateSuccessRateWindowRequest) returns (UpdateSuccessRateWindowResponse);
rpc InvalidateWindows (InvalidateWindowsRequest) returns (InvalidateWindowsResponse);
+
+ rpc FetchEntityAndGlobalSuccessRate (CalGlobalSuccessRateRequest) returns (CalGlobalSuccessRateResponse);
}
// API-1 types
@@ -20,6 +22,12 @@ message CalSuccessRateRequest {
message CalSuccessRateConfig {
uint32 min_aggregates_size = 1;
double default_success_rate = 2;
+ optional SuccessRateSpecificityLevel specificity_level = 3;
+}
+
+enum SuccessRateSpecificityLevel {
+ ENTITY = 0;
+ GLOBAL = 1;
}
message CalSuccessRateResponse {
@@ -31,12 +39,13 @@ message LabelWithScore {
string label = 2;
}
- // API-2 types
+// API-2 types
message UpdateSuccessRateWindowRequest {
string id = 1;
string params = 2;
repeated LabelWithStatus labels_with_status = 3;
UpdateSuccessRateWindowConfig config = 4;
+ repeated LabelWithStatus global_labels_with_status = 5;
}
message LabelWithStatus {
@@ -68,9 +77,28 @@ message InvalidateWindowsRequest {
}
message InvalidateWindowsResponse {
- enum InvalidationStatus {
+ enum InvalidationStatus {
WINDOW_INVALIDATION_SUCCEEDED = 0;
WINDOW_INVALIDATION_FAILED = 1;
}
InvalidationStatus status = 1;
+}
+
+// API-4 types
+message CalGlobalSuccessRateRequest {
+ string entity_id = 1;
+ string entity_params = 2;
+ repeated string entity_labels = 3;
+ repeated string global_labels = 4;
+ CalGlobalSuccessRateConfig config = 5;
+}
+
+message CalGlobalSuccessRateConfig {
+ uint32 entity_min_aggregates_size = 1;
+ double entity_default_success_rate = 2;
+}
+
+message CalGlobalSuccessRateResponse {
+ repeated LabelWithScore entity_scores_with_labels = 1;
+ repeated LabelWithScore global_scores_with_labels = 2;
}
\ No newline at end of file
|
feat
|
Integrate global success rates (#6950)
|
30fe9d19e4955035a370f8f9ce37963cdb76c68a
|
2023-12-18 21:31:06
|
Shanks
|
fix(euclid_wasm): add function to retrieve keys for 3ds and surcharge decision manager (#3160)
| false
|
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs
index 78c7677fe75..134016191f5 100644
--- a/crates/euclid_wasm/src/lib.rs
+++ b/crates/euclid_wasm/src/lib.rs
@@ -6,7 +6,10 @@ use std::{
str::FromStr,
};
-use api_models::{admin as admin_api, routing::ConnectorSelection};
+use api_models::{
+ admin as admin_api, conditional_configs::ConditionalConfigs, routing::ConnectorSelection,
+ surcharge_decision_configs::SurchargeDecisionConfigs,
+};
use common_enums::RoutableConnectors;
use currency_conversion::{
conversion::convert as convert_currency, types as currency_conversion_types,
@@ -20,7 +23,7 @@ use euclid::{
},
frontend::{
ast,
- dir::{self, enums as dir_enums},
+ dir::{self, enums as dir_enums, EuclidDirFilter},
},
};
use once_cell::sync::OnceCell;
@@ -205,6 +208,18 @@ pub fn get_key_type(key: &str) -> Result<String, String> {
Ok(key_str)
}
+#[wasm_bindgen(js_name = getThreeDsKeys)]
+pub fn get_three_ds_keys() -> JsResult {
+ let keys = <ConditionalConfigs as EuclidDirFilter>::ALLOWED;
+ Ok(serde_wasm_bindgen::to_value(keys)?)
+}
+
+#[wasm_bindgen(js_name= getSurchargeKeys)]
+pub fn get_surcharge_keys() -> JsResult {
+ let keys = <SurchargeDecisionConfigs as EuclidDirFilter>::ALLOWED;
+ Ok(serde_wasm_bindgen::to_value(keys)?)
+}
+
#[wasm_bindgen(js_name=parseToString)]
pub fn parser(val: String) -> String {
ron_parser::my_parse(val)
|
fix
|
add function to retrieve keys for 3ds and surcharge decision manager (#3160)
|
346d2d7ad647dd66f2016207ecaaec3fe365beb1
|
2024-08-27 20:38:38
|
Amisha Prabhat
|
fix(routing): fix routing routes to deserialise correctly (#5724)
| false
|
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 267a3d55ce4..d5a3a96d155 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -428,18 +428,15 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: routing_types::RoutingAlgorithmId,
+ algorithm_id: String,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
- let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
- merchant_account.get_id(),
- &algorithm_id.routing_algorithm_id,
- db,
- )
- .await?;
+ let routing_algorithm =
+ RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id, db)
+ .await?;
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
@@ -464,7 +461,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- algorithm_id: routing_types::RoutingAlgorithmId,
+ algorithm_id: String,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
@@ -472,7 +469,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
- &algorithm_id.routing_algorithm_id,
+ &algorithm_id,
merchant_account.get_id(),
)
.await
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 61d89e5e773..ecce0f96198 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -60,7 +60,7 @@ pub async fn routing_create_config(
pub async fn routing_link_config(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<routing_types::RoutingAlgorithmId>,
+ path: web::Path<String>,
transaction_type: &enums::TransactionType,
) -> impl Responder {
let flow = Flow::RoutingLinkConfig;
@@ -74,7 +74,7 @@ pub async fn routing_link_config(
state,
auth.merchant_account,
auth.key_store,
- algorithm.routing_algorithm_id,
+ algorithm,
transaction_type,
)
},
@@ -139,7 +139,7 @@ pub async fn routing_link_config(
pub async fn routing_retrieve_config(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<routing_types::RoutingAlgorithmId>,
+ path: web::Path<String>,
) -> impl Responder {
let algorithm_id = path.into_inner();
let flow = Flow::RoutingRetrieveConfig;
|
fix
|
fix routing routes to deserialise correctly (#5724)
|
54c3fc349d80d1d60a1678183dd0233eb0243b5d
|
2022-11-29 15:27:35
|
Kartikeya Hegde
|
feat: 3ds2 Integration (#35)
| false
|
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 82d586c0f6d..b4c3c6f28bc 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -304,24 +304,11 @@ impl
data: &types::PaymentsRouterData,
res: Response,
) -> CustomResult<types::PaymentsRouterData, errors::ConnectorError> {
- let response = match data.payment_method {
- types::storage::enums::PaymentMethodType::Wallet => {
- let response: adyen::AdyenWalletResponse = res
- .response
- .parse_struct("AdyenWalletResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
- adyen::AdyenPaymentResponse::AdyenWalletResponse(response)
- }
- _ => {
- let response: adyen::AdyenResponse = res
- .response
- .parse_struct("AdyenResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response: adyen::AdyenPaymentResponse = res
+ .response
+ .parse_struct("AdyenPaymentResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- adyen::AdyenPaymentResponse::AdyenResponse(response)
- }
- };
types::RouterData::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 81bfb2807ff..d76081635ca 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1,3 +1,5 @@
+use std::{collections::HashMap, str::FromStr};
+
use error_stack::{IntoReport, ResultExt};
use reqwest::Url;
use serde::{Deserialize, Serialize};
@@ -29,7 +31,7 @@ pub enum AdyenRecurringModel {
UnscheduledCardOnFile,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenPaymentRequest {
amount: Amount,
@@ -37,11 +39,25 @@ pub struct AdyenPaymentRequest {
payment_method: AdyenPaymentMethod,
reference: String,
return_url: String,
+ browser_info: Option<AdyenBrowserInfo>,
shopper_interaction: AdyenShopperInteraction,
#[serde(skip_serializing_if = "Option::is_none")]
recurring_processing_model: Option<AdyenRecurringModel>,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct AdyenBrowserInfo {
+ user_agent: String,
+ accept_header: String,
+ language: String,
+ color_depth: u8,
+ screen_height: u32,
+ screen_width: u32,
+ time_zone_offset: i32,
+ java_enabled: bool,
+}
+
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct AdyenRedirectRequest {
pub details: AdyenRedirectRequestTypes,
@@ -78,7 +94,7 @@ pub struct AdyenThreeDS {
#[serde(untagged)]
pub enum AdyenPaymentResponse {
AdyenResponse(AdyenResponse),
- AdyenWalletResponse(AdyenWalletResponse),
+ AdyenRedirectResponse(AdyenWalletResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -109,6 +125,7 @@ pub struct AdyenWalletAction {
method: String,
#[serde(rename = "type")]
type_of_response: String,
+ data: HashMap<String, String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
@@ -194,6 +211,27 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType {
}
}
}
+
+impl TryFrom<&types::BrowserInformation> for AdyenBrowserInfo {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::BrowserInformation) -> Result<Self, Self::Error> {
+ Ok(Self {
+ accept_header: item.accept_header.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "accept_header".to_string(),
+ },
+ )?,
+ language: item.language.clone(),
+ screen_height: item.screen_height,
+ screen_width: item.screen_width,
+ color_depth: item.color_depth,
+ user_agent: item.user_agent.clone(),
+ time_zone_offset: item.time_zone,
+ java_enabled: item.java_enabled,
+ })
+ }
+}
+
// Payment Request Transform
impl TryFrom<&types::PaymentsRouterData> for AdyenPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
@@ -253,14 +291,29 @@ impl TryFrom<&types::PaymentsRouterData> for AdyenPaymentRequest {
}),
}?;
+ let browser_info = if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) {
+ item.request
+ .browser_info
+ .clone()
+ .map(|d| AdyenBrowserInfo::try_from(&d))
+ .transpose()?
+ } else {
+ None
+ };
+
Ok(AdyenPaymentRequest {
amount,
merchant_account: auth_type.merchant_account,
payment_method,
reference,
- return_url: "juspay.io".to_string(),
+ return_url: item.orca_return_url.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "orca_return_url".into(),
+ },
+ )?,
shopper_interaction,
recurring_processing_model,
+ browser_info,
})
}
}
@@ -379,12 +432,10 @@ pub fn get_wallet_response(
let redirection_data = services::RedirectForm {
url: redirection_url_response.to_string(),
- method: services::Method::Get,
- form_fields: std::collections::HashMap::from_iter(
- redirection_url_response
- .query_pairs()
- .map(|(k, v)| (k.to_string(), v.to_string())),
- ),
+ method: services::Method::from_str(&response.action.method)
+ .into_report()
+ .change_context(errors::ParsingError)?,
+ form_fields: response.action.data,
};
let payments_response_data = types::PaymentsResponseData {
@@ -405,7 +456,7 @@ impl<F, Req>
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) = match item.response {
AdyenPaymentResponse::AdyenResponse(response) => get_adyen_response(response)?,
- AdyenPaymentResponse::AdyenWalletResponse(response) => get_wallet_response(response)?,
+ AdyenPaymentResponse::AdyenRedirectResponse(response) => get_wallet_response(response)?,
};
Ok(types::RouterData {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 9e1a744055b..1fbb61654aa 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -26,7 +26,7 @@ use crate::{
enums::{self, IntentStatus},
},
},
- utils::OptionExt,
+ utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(ops = "all", flow = "authorize")]
@@ -70,6 +70,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let billing_address =
helpers::get_address_for_payment_request(db, request.billing.as_ref(), None).await?;
+ let browser_info = request
+ .browser_info
+ .clone()
+ .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "browser_info",
+ })?;
+
payment_attempt = match db
.insert_payment_attempt(Self::make_payment_attempt(
&payment_id,
@@ -78,6 +87,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
money,
payment_method_type,
request,
+ browser_info,
))
.await
{
@@ -287,6 +297,7 @@ impl PaymentCreate {
money: (i32, enums::Currency),
payment_method: Option<enums::PaymentMethodType>,
request: &api::PaymentsRequest,
+ browser_info: Option<serde_json::Value>,
) -> storage::PaymentAttemptNew {
let created_at @ modified_at @ last_synced = Some(crate::utils::date_time::now());
let status =
@@ -308,6 +319,7 @@ impl PaymentCreate {
modified_at,
last_synced,
authentication_type: request.authentication_type,
+ browser_info,
..storage::PaymentAttemptNew::default()
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index a09d474a3a9..dc78f6dccbe 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -255,6 +255,14 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> {
+ let browser_info: Option<types::BrowserInformation> = payment_data
+ .payment_attempt
+ .browser_info
+ .map(|b| b.parse_value("BrowserInformation"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "browser_info",
+ })?;
Ok(Self {
payment_method_data: {
let payment_method_type = payment_data
@@ -276,6 +284,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsRequestData {
confirm: payment_data.payment_attempt.confirm,
statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix,
capture_method: payment_data.payment_attempt.capture_method,
+ browser_info,
})
}
}
diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs
index e7682cebfed..1c367303f0b 100644
--- a/crates/router/src/db/payment_attempt.rs
+++ b/crates/router/src/db/payment_attempt.rs
@@ -200,6 +200,7 @@ mod storage {
amount_to_capture: payment_attempt.amount_to_capture,
cancellation_reason: payment_attempt.cancellation_reason.clone(),
mandate_id: payment_attempt.mandate_id.clone(),
+ browser_info: payment_attempt.browser_info.clone(),
};
// TODO: Add a proper error for serialization failure
let redis_value = serde_json::to_string(&created_attempt)
diff --git a/crates/router/src/schema.rs b/crates/router/src/schema.rs
index d4d7b89595b..7dd78457a82 100644
--- a/crates/router/src/schema.rs
+++ b/crates/router/src/schema.rs
@@ -203,6 +203,7 @@ diesel::table! {
cancellation_reason -> Nullable<Varchar>,
amount_to_capture -> Nullable<Int4>,
mandate_id -> Nullable<Varchar>,
+ browser_info -> Nullable<Jsonb>,
}
}
diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs
index 1c5c2f7a101..8f455a87362 100644
--- a/crates/router/src/services/api/request.rs
+++ b/crates/router/src/services/api/request.rs
@@ -12,7 +12,9 @@ use crate::{
pub(crate) type Headers = Vec<(String, String)>;
-#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display)]
+#[derive(
+ Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString,
+)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum Method {
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 8677347dab8..981954086c8 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -75,6 +75,7 @@ pub struct PaymentsRequestData {
pub mandate_id: Option<String>,
pub off_session: Option<bool>,
pub setup_mandate_details: Option<payments::MandateData>,
+ pub browser_info: Option<BrowserInformation>,
}
#[derive(Debug, Clone)]
@@ -112,7 +113,7 @@ pub struct RefundsRequestData {
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct DeviceInformation {
+pub struct BrowserInformation {
pub color_depth: u8,
pub java_enabled: bool,
pub java_script_enabled: bool,
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index bdd79cd6410..300871a1e16 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -50,6 +50,7 @@ pub struct PaymentsRequest {
pub payment_token: Option<i32>,
pub shipping: Option<Address>,
pub billing: Option<Address>,
+ pub browser_info: Option<types::BrowserInformation>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: Option<serde_json::Value>,
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 5d04890829f..3d14de11ed5 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -35,6 +35,7 @@ pub struct PaymentAttempt {
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<i32>,
pub mandate_id: Option<String>,
+ pub browser_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)]
@@ -68,6 +69,7 @@ pub struct PaymentAttemptNew {
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<i32>,
pub mandate_id: Option<String>,
+ pub browser_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug)]
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index e88fe2caec5..3245a453c34 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -46,6 +46,7 @@ fn construct_payment_router_data() -> types::PaymentsRouterData {
off_session: None,
setup_mandate_details: None,
capture_method: None,
+ browser_info: None,
},
response: None,
payment_method_id: None,
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index defe0e28ba5..d3ad85344dd 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -46,6 +46,7 @@ fn construct_payment_router_data() -> types::PaymentsRouterData {
off_session: None,
setup_mandate_details: None,
capture_method: None,
+ browser_info: None,
},
payment_method_id: None,
response: None,
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index e09ae1f838f..3d95d5babd3 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -42,6 +42,7 @@ fn construct_payment_router_data() -> types::PaymentsRouterData {
off_session: None,
setup_mandate_details: None,
capture_method: None,
+ browser_info: None,
},
response: None,
payment_method_id: None,
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 6ee96ecb41b..acbfd3ee70c 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -326,6 +326,7 @@ async fn payments_create_core() {
mandate_id: None,
off_session: None,
client_secret: None,
+ browser_info: None,
};
let expected_response = api::PaymentsResponse {
@@ -484,6 +485,7 @@ async fn payments_create_core_adyen_no_redirect() {
mandate_id: None,
off_session: None,
client_secret: None,
+ browser_info: None,
};
let expected_response = services::BachResponse::Json(api::PaymentsResponse {
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 27bff1b3573..09aac122fd4 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -91,6 +91,7 @@ async fn payments_create_core() {
mandate_id: None,
off_session: None,
client_secret: None,
+ browser_info: None,
};
let expected_response = api::PaymentsResponse {
@@ -252,6 +253,7 @@ async fn payments_create_core_adyen_no_redirect() {
off_session: None,
mandate_id: None,
client_secret: None,
+ browser_info: None,
};
let expected_response = services::BachResponse::Json(api::PaymentsResponse {
diff --git a/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/down.sql b/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/down.sql
new file mode 100644
index 00000000000..b172b43b73b
--- /dev/null
+++ b/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE payment_attempt
+DROP COLUMN browser_info;
diff --git a/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql b/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql
new file mode 100644
index 00000000000..a072f6cb3bf
--- /dev/null
+++ b/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE payment_attempt
+ADD COLUMN browser_info JSONB DEFAULT '{}'::JSONB;
|
feat
|
3ds2 Integration (#35)
|
57887bdf3a892548afea80859c2553d5a1cca49d
|
2023-08-02 17:17:34
|
Prasunna Soppa
|
feat(connector): add support for bank redirect for Paypal (#1107)
| false
|
diff --git a/.github/testcases/ui_tests.json b/.github/testcases/ui_tests.json
index e0445ce8e8d..f85ffa23d9d 100644
--- a/.github/testcases/ui_tests.json
+++ b/.github/testcases/ui_tests.json
@@ -1,5 +1,4 @@
{
- "tests_to_ignore": [],
"1": {
"id": 1,
"name": "stripe giropay",
@@ -1348,6 +1347,75 @@
"id": 225,
"name": "Boleto Bancario",
"connector": "adyen_uk",
- "request": "{\"amount\":6540,\"currency\":\"BRL\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com/\",\"payment_method\":\"voucher\",\"payment_method_type\":\"boleto_bancario\",\"payment_method_data\":{\"voucher\":{\"boleto_bancario\":{\"social_security_number\":\"56861752509\"}}}}"
- }
-}
+ "request": "{\"amount\":6540,\"currency\":\"BRL\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com/\",\"payment_method\":\"voucher\",\"payment_method_type\":\"boleto\",\"payment_method_data\":{\"voucher\":{\"boleto\":{\"social_security_number\":\"56861752509\"}}}}"
+ },
+ "227": {
+ "id": 227,
+ "name": "authorizedotnet payment success for webhook",
+ "connector": "authorizedotnet",
+ "request": "{\"amount\":400,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":40,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"5424000000000015\",\"card_exp_month\":\"01\",\"card_exp_year\":\"2025\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"CA\",\"line3\":\"CA\",\"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\":\"CA\",\"line3\":\"CA\",\"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,\"ip_address\":\"127.2.2.0\",\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "228": {
+ "id": 228,
+ "name": "BNI VA",
+ "connector": "adyen_uk",
+ "request": "{\"amount\":6540,\"currency\":\"IDR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com/\",\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"bni_va\",\"payment_method_data\":{\"bank_transfer\":{\"bni_va_bank_transfer\":{\"billing_details\":{\"first_name\":\"Some\",\"second_name\":\"one\",\"email\":\"[email protected]\"}}}}}"
+ },
+ "229": {
+ "id": 229,
+ "name": "pay_JbukS3WUqF6MVjTp2fe1",
+ "connector": "adyen",
+ "request": "{\"amount\":7000,\"currency\":\"SEK\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"payment_method\":\"pay_later\",\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"klarna_redirect\":{\"billing_email\":\"[email protected]\",\"billing_country\":\"SE\"}}}}"
+ },
+ "230": {
+ "id": 230,
+ "name": "Indonesian Alfamart",
+ "connector": "adyen_uk",
+ "request": "{\"amount\":6540,\"currency\":\"IDR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com/\",\"payment_method\":\"voucher\",\"payment_method_type\":\"alfamart\",\"payment_method_data\":{\"voucher\":{\"alfamart\":{\"first_name\":\"Some\",\"second_name\":\"one\",\"email\":\"[email protected]\"}}}}"
+ },
+ "231": {
+ "id": 231,
+ "name": "Indonesian Bank Transfer Permata",
+ "connector": "adyen_uk",
+ "request": "{\"amount\":6540,\"currency\":\"IDR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com/\",\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"permata_bank_transfer\",\"payment_method_data\":{\"bank_transfer\":{\"permata_bank_transfer\":{\"billing_details\":{\"first_name\":\"Some\",\"second_name\":\"one\",\"email\":\"[email protected]\"}}}}}"
+ },
+ "232": {
+ "id": 232,
+ "name": "Adyen Open Banking UK",
+ "connector": "adyen_uk",
+ "request": "{\"amount\":6540,\"currency\":\"GBP\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"payment_method\":\"bank_redirect\",\"payment_method_data\":{\"bank_redirect\":{\"open_banking_uk\":{\"issuer\":\"open_bank_success\",\"country\":\"GB\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"GB\",\"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\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"GB\",\"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\"}}"
+ },
+ "233": {
+ "id": 233,
+ "name": "paypal-giropay-success",
+ "connector": "paypal",
+ "request": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"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\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"giropay\",\"payment_method_data\":{\"bank_redirect\":{\"giropay\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"DE\"}}}}"
+ },
+ "234": {
+ "id": 234,
+ "name": "paypal-eps-success",
+ "connector": "paypal",
+ "request": "{\"amount\":12300,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":12300,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"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\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"AT\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"american_express\",\"preferred_language\":\"en\",\"country\":\"AT\"}}}}"
+ },
+ "235": {
+ "id": 235,
+ "name": "paypal-sofort-success",
+ "connector": "paypal",
+ "request": "{\"amount\":1100,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1100,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"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\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"AT\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"sofort\",\"payment_method_data\":{\"bank_redirect\":{\"sofort\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"AT\"}}}}"
+ },
+ "236": {
+ "id": 236,
+ "name": "Adyen Seven Eleven",
+ "connector": "adyen_uk",
+ "request": "{\"amount\":6540,\"currency\":\"JPY\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com/\",\"payment_method\":\"voucher\",\"payment_method_type\":\"seven_eleven\",\"payment_method_data\":{\"voucher\":{\"seven_eleven\":{\"first_name\":\"Some\",\"last_name\":\"One\",\"email\":\"[email protected]\",\"phone_number\":\"1234567890\"}}}}"
+ },
+ "tests_to_ignore": [
+ "noon_ui::should_make_noon_3ds_payment_test",
+ "adyen_uk_ui::should_make_adyen_online_banking_thailand_payment_test",
+ "adyen_uk_ui::should_make_adyen_blik_payment_test",
+ "authorizedotnet_ui::should_make_paypal_payment_test",
+ "multisafepay_ui::should_make_multisafepay_3ds_payment_failed_test",
+ "multisafepay_ui::should_make_multisafepay_3ds_payment_success_test",
+ "nexinets_ui::*"
+ ]
+}
\ No newline at end of file
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 0d1b3f8f9b6..248525fcc40 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -665,3 +665,13 @@ pub struct TokenizedBankTransferValue1 {
pub struct TokenizedBankTransferValue2 {
pub customer_id: Option<String>,
}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct TokenizedBankRedirectValue1 {
+ pub data: payments::BankRedirectData,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct TokenizedBankRedirectValue2 {
+ pub customer_id: Option<String>,
+}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 892590e58ac..5f5294589a5 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -803,6 +803,10 @@ pub enum BankRedirectData {
/// The hyperswitch bank code for eps
#[schema(value_type = BankNames, example = "triodos_bank")]
bank_name: Option<api_enums::BankNames>,
+
+ /// The country for bank payment
+ #[schema(value_type = CountryAlpha2, example = "US")]
+ country: Option<api_enums::CountryAlpha2>,
},
Giropay {
/// The billing details for bank redirection
@@ -816,6 +820,10 @@ pub enum BankRedirectData {
/// Bank account iban
#[schema(value_type = Option<String>)]
bank_account_iban: Option<Secret<String>>,
+
+ /// The country for bank payment
+ #[schema(value_type = CountryAlpha2, example = "US")]
+ country: Option<api_enums::CountryAlpha2>,
},
Ideal {
/// The billing details for bank redirection
@@ -824,6 +832,10 @@ pub enum BankRedirectData {
/// The hyperswitch bank code for ideal
#[schema(value_type = BankNames, example = "abn_amro")]
bank_name: Option<api_enums::BankNames>,
+
+ /// The country for bank payment
+ #[schema(value_type = CountryAlpha2, example = "US")]
+ country: Option<api_enums::CountryAlpha2>,
},
Interac {
/// The country for bank payment
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index ec74a8f0214..4c11529f164 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -54,7 +54,8 @@ impl Paypal {
connector_meta: &Option<serde_json::Value>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
match payment_method {
- Some(diesel_models::enums::PaymentMethod::Wallet) => {
+ Some(diesel_models::enums::PaymentMethod::Wallet)
+ | Some(diesel_models::enums::PaymentMethod::BankRedirect) => {
let meta: PaypalMeta = to_connector_meta(connector_meta.clone())?;
Ok(Some(meta.order_id))
}
@@ -384,7 +385,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
match data.payment_method {
- diesel_models::enums::PaymentMethod::Wallet => {
+ diesel_models::enums::PaymentMethod::Wallet
+ | diesel_models::enums::PaymentMethod::BankRedirect => {
let response: paypal::PaypalRedirectResponse = res
.response
.parse_struct("paypal PaymentsRedirectResponse")
@@ -516,7 +518,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
) -> CustomResult<String, errors::ConnectorError> {
let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?;
match req.payment_method {
- diesel_models::enums::PaymentMethod::Wallet => Ok(format!(
+ diesel_models::enums::PaymentMethod::Wallet
+ | diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!(
"{}v2/checkout/orders/{}",
self.base_url(connectors),
paypal_meta.order_id
@@ -561,7 +564,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
match data.payment_method {
- diesel_models::enums::PaymentMethod::Wallet => {
+ diesel_models::enums::PaymentMethod::Wallet
+ | diesel_models::enums::PaymentMethod::BankRedirect => {
let response: paypal::PaypalOrdersResponse = res
.response
.parse_struct("paypal PaymentsOrderResponse")
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 622651aa9a5..4852016bfe1 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1,3 +1,4 @@
+use api_models::payments::BankRedirectData;
use common_utils::errors::CustomResult;
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -5,8 +6,8 @@ use url::Url;
use crate::{
connector::utils::{
- self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, CardData,
- PaymentsAuthorizeRequestData,
+ self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData,
+ BankRedirectBillingData, CardData, PaymentsAuthorizeRequestData,
},
core::errors,
services,
@@ -58,6 +59,7 @@ pub struct RedirectRequest {
#[derive(Debug, Serialize)]
pub struct ContextStruct {
return_url: Option<String>,
+ cancel_url: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -70,6 +72,10 @@ pub struct PaypalRedirectionRequest {
pub enum PaymentSourceItem {
Card(CardRequest),
Paypal(PaypalRedirectionRequest),
+ IDeal(RedirectRequest),
+ Eps(RedirectRequest),
+ Giropay(RedirectRequest),
+ Sofort(RedirectRequest),
}
#[derive(Debug, Serialize)]
@@ -93,6 +99,68 @@ fn get_address_info(
};
Ok(address)
}
+fn get_payment_source(
+ item: &types::PaymentsAuthorizeRouterData,
+ bank_redirection_data: &BankRedirectData,
+) -> Result<PaymentSourceItem, error_stack::Report<errors::ConnectorError>> {
+ match bank_redirection_data {
+ BankRedirectData::Eps {
+ billing_details,
+ bank_name: _,
+ country,
+ } => Ok(PaymentSourceItem::Eps(RedirectRequest {
+ name: billing_details.get_billing_name()?,
+ country_code: country.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "eps.country",
+ })?,
+ experience_context: ContextStruct {
+ return_url: item.request.complete_authorize_url.clone(),
+ cancel_url: item.request.complete_authorize_url.clone(),
+ },
+ })),
+ BankRedirectData::Giropay {
+ billing_details,
+ country,
+ ..
+ } => Ok(PaymentSourceItem::Giropay(RedirectRequest {
+ name: billing_details.get_billing_name()?,
+ country_code: country.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "giropay.country",
+ })?,
+ experience_context: ContextStruct {
+ return_url: item.request.complete_authorize_url.clone(),
+ cancel_url: item.request.complete_authorize_url.clone(),
+ },
+ })),
+ BankRedirectData::Ideal {
+ billing_details,
+ bank_name: _,
+ country,
+ } => Ok(PaymentSourceItem::IDeal(RedirectRequest {
+ name: billing_details.get_billing_name()?,
+ country_code: country.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "ideal.country",
+ })?,
+ experience_context: ContextStruct {
+ return_url: item.request.complete_authorize_url.clone(),
+ cancel_url: item.request.complete_authorize_url.clone(),
+ },
+ })),
+ BankRedirectData::Sofort {
+ country,
+ preferred_language: _,
+ billing_details,
+ } => Ok(PaymentSourceItem::Sofort(RedirectRequest {
+ name: billing_details.get_billing_name()?,
+ country_code: *country,
+ experience_context: ContextStruct {
+ return_url: item.request.complete_authorize_url.clone(),
+ cancel_url: item.request.complete_authorize_url.clone(),
+ },
+ })),
+ _ => Err(errors::ConnectorError::NotImplemented("Bank Redirect".to_string()).into()),
+ }
+}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
@@ -152,6 +220,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest {
Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
+ cancel_url: item.request.complete_authorize_url.clone(),
},
}));
@@ -165,6 +234,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest {
"Payment Method".to_string(),
))?,
},
+ api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
+ let intent = match item.request.is_auto_capture()? {
+ true => PaypalPaymentIntent::Capture,
+ false => Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Manual capture method for Bank Redirect".to_string(),
+ connector: "Paypal".to_string(),
+ })?,
+ };
+ let amount = OrderAmount {
+ currency_code: item.request.currency,
+ value: item.request.amount.to_string(),
+ };
+ let reference_id = item.attempt_id.clone();
+ let purchase_units = vec![PurchaseUnitRequest {
+ reference_id,
+ amount,
+ }];
+ let payment_source = Some(get_payment_source(item, bank_redirection_data)?);
+
+ Ok(Self {
+ intent,
+ purchase_units,
+ payment_source,
+ })
+ }
_ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()),
}
}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 221ad0487bf..e7f36449640 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -795,6 +795,18 @@ impl AddressDetailsData for api::AddressDetails {
}
}
+pub trait BankRedirectBillingData {
+ fn get_billing_name(&self) -> Result<Secret<String>, Error>;
+}
+
+impl BankRedirectBillingData for payments::BankRedirectBilling {
+ fn get_billing_name(&self) -> Result<Secret<String>, Error> {
+ self.billing_name
+ .clone()
+ .ok_or_else(missing_field_err("billing_details.billing_name"))
+ }
+}
+
pub trait MandateData {
fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error>;
fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error>;
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 6dca567567c..5a504a0facc 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -211,12 +211,57 @@ impl Vaultable for api::WalletData {
}
}
+impl Vaultable for api_models::payments::BankRedirectData {
+ fn get_value1(&self, _customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
+ let value1 = api_models::payment_methods::TokenizedBankRedirectValue1 {
+ data: self.to_owned(),
+ };
+
+ utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue1>::encode_to_string_of_json(&value1)
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode bank redirect data")
+ }
+
+ fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
+ let value2 = api_models::payment_methods::TokenizedBankRedirectValue2 { customer_id };
+
+ utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue2>::encode_to_string_of_json(&value2)
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode bank redirect supplementary data")
+ }
+
+ fn from_values(
+ value1: String,
+ value2: String,
+ ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
+ let value1: api_models::payment_methods::TokenizedBankRedirectValue1 = value1
+ .parse_struct("TokenizedBankRedirectValue1")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Could not deserialize into bank redirect data")?;
+
+ let value2: api_models::payment_methods::TokenizedBankRedirectValue2 = value2
+ .parse_struct("TokenizedBankRedirectValue2")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Could not deserialize into supplementary bank redirect data")?;
+
+ let bank_transfer_data = value1.data;
+
+ let supp_data = SupplementaryVaultData {
+ customer_id: value2.customer_id,
+ payment_method_id: None,
+ };
+
+ Ok((bank_transfer_data, supp_data))
+ }
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum VaultPaymentMethod {
Card(String),
Wallet(String),
BankTransfer(String),
+ BankRedirect(String),
}
impl Vaultable for api::PaymentMethodData {
@@ -227,6 +272,9 @@ impl Vaultable for api::PaymentMethodData {
Self::BankTransfer(bank_transfer) => {
VaultPaymentMethod::BankTransfer(bank_transfer.get_value1(customer_id)?)
}
+ Self::BankRedirect(bank_redirect) => {
+ VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?)
+ }
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.into_report()
.attach_printable("Payment method not supported")?,
@@ -244,6 +292,9 @@ impl Vaultable for api::PaymentMethodData {
Self::BankTransfer(bank_transfer) => {
VaultPaymentMethod::BankTransfer(bank_transfer.get_value2(customer_id)?)
}
+ Self::BankRedirect(bank_redirect) => {
+ VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?)
+ }
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.into_report()
.attach_printable("Payment method not supported")?,
@@ -285,6 +336,15 @@ impl Vaultable for api::PaymentMethodData {
api_models::payments::BankTransferData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankTransfer(Box::new(bank_transfer)), supp_data))
}
+ (
+ VaultPaymentMethod::BankRedirect(mvalue1),
+ VaultPaymentMethod::BankRedirect(mvalue2),
+ ) => {
+ let (bank_redirect, supp_data) =
+ api_models::payments::BankRedirectData::from_values(mvalue1, mvalue2)?;
+ Ok((Self::BankRedirect(bank_redirect), supp_data))
+ }
+
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.into_report()
.attach_printable("Payment method not supported"),
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 326ac771960..2970034d84c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1258,6 +1258,11 @@ pub async fn make_pm_data<'a, F: Clone, R>(
Some(storage_enums::PaymentMethod::BankTransfer);
pm
}
+ Some(api::PaymentMethodData::BankRedirect(_)) => {
+ payment_data.payment_attempt.payment_method =
+ Some(storage_enums::PaymentMethod::BankRedirect);
+ pm
+ }
Some(_) => Err(errors::ApiErrorResponse::InternalServerError)
.into_report()
.attach_printable(
@@ -1280,7 +1285,6 @@ pub async fn make_pm_data<'a, F: Clone, R>(
Ok(pm_opt.to_owned())
}
(pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::BankRedirect(_)), _) => Ok(pm.to_owned()),
(pm @ Some(api::PaymentMethodData::Crypto(_)), _) => Ok(pm.to_owned()),
(pm @ Some(api::PaymentMethodData::BankDebit(_)), _) => Ok(pm.to_owned()),
(pm @ Some(api::PaymentMethodData::Upi(_)), _) => Ok(pm.to_owned()),
@@ -1311,6 +1315,18 @@ pub async fn make_pm_data<'a, F: Clone, R>(
payment_data.token = Some(token);
Ok(pm_opt.to_owned())
}
+ (pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)), _) => {
+ let token = vault::Vault::store_payment_method_data_in_locker(
+ state,
+ None,
+ pm,
+ payment_data.payment_intent.customer_id.to_owned(),
+ enums::PaymentMethod::BankRedirect,
+ )
+ .await?;
+ payment_data.token = Some(token);
+ Ok(pm_opt.to_owned())
+ }
_ => Ok(None),
}?;
diff --git a/crates/test_utils/tests/connectors/paypal_ui.rs b/crates/test_utils/tests/connectors/paypal_ui.rs
index 3e9fc162dc2..6f08c87be2e 100644
--- a/crates/test_utils/tests/connectors/paypal_ui.rs
+++ b/crates/test_utils/tests/connectors/paypal_ui.rs
@@ -19,8 +19,8 @@ async fn should_make_paypal_paypal_wallet_payment(
web_driver,
&format!("{CHEKOUT_BASE_URL}/saved/21"),
vec![
- Event::Trigger(Trigger::Click(By::Css(".reviewButton"))),
- Event::Assert(Assert::IsPresent("How Search works")),
+ Event::Trigger(Trigger::Click(By::Css("#payment-submit-btn"))),
+ Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"],
@@ -31,8 +31,92 @@ async fn should_make_paypal_paypal_wallet_payment(
Ok(())
}
+async fn should_make_paypal_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
+ let conn = PaypalSeleniumTest {};
+ conn.make_redirection_payment(
+ web_driver,
+ vec![
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/181"))),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ Event::Trigger(Trigger::Click(By::Name("Successful"))),
+ Event::Assert(Assert::IsPresent("processing")),
+ ],
+ )
+ .await?;
+ Ok(())
+}
+
+async fn should_make_paypal_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
+ let conn = PaypalSeleniumTest {};
+ conn.make_redirection_payment(
+ web_driver,
+ vec![
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/233"))),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ Event::Trigger(Trigger::Click(By::Name("Successful"))),
+ Event::Assert(Assert::IsPresent("processing")),
+ ],
+ )
+ .await?;
+ Ok(())
+}
+
+async fn should_make_paypal_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
+ let conn = PaypalSeleniumTest {};
+ conn.make_redirection_payment(
+ web_driver,
+ vec![
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/234"))),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ Event::Trigger(Trigger::Click(By::Name("Successful"))),
+ Event::Assert(Assert::IsPresent("processing")),
+ ],
+ )
+ .await?;
+ Ok(())
+}
+
+async fn should_make_paypal_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
+ let conn = PaypalSeleniumTest {};
+ conn.make_redirection_payment(
+ web_driver,
+ vec![
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/235"))),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ Event::Trigger(Trigger::Click(By::Name("Successful"))),
+ Event::Assert(Assert::IsPresent("processing")),
+ ],
+ )
+ .await?;
+ Ok(())
+}
+
#[test]
#[serial]
fn should_make_paypal_paypal_wallet_payment_test() {
tester!(should_make_paypal_paypal_wallet_payment);
}
+
+#[test]
+#[serial]
+fn should_make_paypal_ideal_payment_test() {
+ tester!(should_make_paypal_ideal_payment);
+}
+
+#[test]
+#[serial]
+fn should_make_paypal_giropay_payment_test() {
+ tester!(should_make_paypal_giropay_payment);
+}
+
+#[test]
+#[serial]
+fn should_make_paypal_eps_payment_test() {
+ tester!(should_make_paypal_eps_payment);
+}
+
+#[test]
+#[serial]
+fn should_make_paypal_sofort_payment_test() {
+ tester!(should_make_paypal_sofort_payment);
+}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 4db52f964b3..e4d0c4bc5f0 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -2827,7 +2827,8 @@
"type": "object",
"required": [
"billing_details",
- "bank_name"
+ "bank_name",
+ "country"
],
"properties": {
"billing_details": {
@@ -2835,6 +2836,9 @@
},
"bank_name": {
"$ref": "#/components/schemas/BankNames"
+ },
+ "country": {
+ "$ref": "#/components/schemas/CountryAlpha2"
}
}
}
@@ -2849,7 +2853,8 @@
"giropay": {
"type": "object",
"required": [
- "billing_details"
+ "billing_details",
+ "country"
],
"properties": {
"billing_details": {
@@ -2864,6 +2869,9 @@
"type": "string",
"description": "Bank account iban",
"nullable": true
+ },
+ "country": {
+ "$ref": "#/components/schemas/CountryAlpha2"
}
}
}
@@ -2879,7 +2887,8 @@
"type": "object",
"required": [
"billing_details",
- "bank_name"
+ "bank_name",
+ "country"
],
"properties": {
"billing_details": {
@@ -2887,6 +2896,9 @@
},
"bank_name": {
"$ref": "#/components/schemas/BankNames"
+ },
+ "country": {
+ "$ref": "#/components/schemas/CountryAlpha2"
}
}
}
|
feat
|
add support for bank redirect for Paypal (#1107)
|
595f34e20f84bf1b62461ffae4631b6fad888d32
|
2022-11-29 23:34:05
|
Kartikeya Hegde
|
chore: Remove option from user-agent field (#41)
| false
|
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index d76081635ca..ec067a97dea 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -216,11 +216,7 @@ impl TryFrom<&types::BrowserInformation> for AdyenBrowserInfo {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::BrowserInformation) -> Result<Self, Self::Error> {
Ok(Self {
- accept_header: item.accept_header.clone().ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "accept_header".to_string(),
- },
- )?,
+ accept_header: item.accept_header.clone(),
language: item.language.clone(),
screen_height: item.screen_height,
screen_width: item.screen_width,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 981954086c8..a8c4c9927bc 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -122,7 +122,7 @@ pub struct BrowserInformation {
pub screen_width: u32,
pub time_zone: i32,
pub ip_address: Option<std::net::IpAddr>,
- pub accept_header: Option<String>,
+ pub accept_header: String,
pub user_agent: String,
}
diff --git a/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql b/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql
index a072f6cb3bf..474e748d3f8 100644
--- a/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql
+++ b/migrations/2022-11-24-095709_add_browser_info_to_payment_attempt/up.sql
@@ -1,2 +1,2 @@
ALTER TABLE payment_attempt
-ADD COLUMN browser_info JSONB DEFAULT '{}'::JSONB;
+ADD COLUMN browser_info JSONB DEFAULT NULL;
|
chore
|
Remove option from user-agent field (#41)
|
ca749b32591edcbf4676da4327f8b6ccbc839d4b
|
2024-07-22 15:59:59
|
Prajjwal Kumar
|
refactor(core): change primary keys in payment_methods table (#5393)
| false
|
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index b8c5344cbbb..55f8e935b14 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -934,7 +934,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- payment_methods (id) {
+ payment_methods (payment_method_id) {
id -> Int4,
#[max_length = 64]
customer_id -> Varchar,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 164600c88ac..90046d3fd95 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -931,7 +931,7 @@ diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
- payment_methods (id) {
+ payment_methods (payment_method_id) {
id -> Int4,
#[max_length = 64]
customer_id -> Varchar,
diff --git a/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/down.sql b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/down.sql
new file mode 100644
index 00000000000..26dd04d739b
--- /dev/null
+++ b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/down.sql
@@ -0,0 +1,5 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey;
+
+ALTER TABLE payment_methods
+ADD PRIMARY KEY (id);
diff --git a/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/up.sql b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/up.sql
new file mode 100644
index 00000000000..5fc305bc92c
--- /dev/null
+++ b/migrations/2024-07-22-082828_change_primary_key_for_payment_methods/up.sql
@@ -0,0 +1,12 @@
+-- Your SQL goes here
+-- The below query will lock the payment_methods table
+-- Running this query is not necessary on higher environments
+-- as the application will work fine without these queries being run
+-- This query should be run after the new version of application is deployed
+ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey;
+
+-- Use the `payment_method_id` column as primary key
+-- This is already unique, not null column
+-- So this query should not fail for not null or duplicate value reasons
+ALTER TABLE payment_methods
+ADD PRIMARY KEY (payment_method_id);
|
refactor
|
change primary keys in payment_methods table (#5393)
|
e4c7ab8e683d969092910b3fcc046c2e65e18df9
|
2025-03-18 18:02:44
|
awasthi21
|
fix(connector): Handle Sequential Automatic case in MIT payments (#6833)
| false
|
diff --git a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
index 7da6b6e95ea..a1136f5eeb0 100644
--- a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs
@@ -1198,7 +1198,9 @@ impl
PayboxAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transaction_type = match item.router_data.request.capture_method {
- Some(enums::CaptureMethod::Automatic) | None => {
+ Some(enums::CaptureMethod::Automatic)
+ | None
+ | Some(enums::CaptureMethod::SequentialAutomatic) => {
Ok(MANDATE_AUTH_AND_CAPTURE_ONLY.to_string())
}
Some(enums::CaptureMethod::Manual) => Ok(MANDATE_AUTH_ONLY.to_string()),
|
fix
|
Handle Sequential Automatic case in MIT payments (#6833)
|
1d4c87a9e37ab1fc05754208ba4fbbcf15ad895a
|
2024-08-01 14:57:39
|
Nishant Joshi
|
feat(auth): Add support for partial-auth, by facilitating injection of authentication parameters in headers (#4802)
| false
|
diff --git a/config/development.toml b/config/development.toml
index e1b180d300a..b380135e195 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -174,6 +174,10 @@ validity = 1
[api_keys]
hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+checksum_auth_context = "TEST"
+checksum_auth_key = "54455354"
+
+
[connectors]
aci.base_url = "https://eu-test.oppwa.com/"
adyen.base_url = "https://checkout-test.adyen.com/"
diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs
index 779781a7d8c..8b8707d9b99 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -238,6 +238,43 @@ impl VerifySignature for HmacSha512 {
}
}
+///
+/// Blake3
+#[derive(Debug)]
+pub struct Blake3(String);
+
+impl Blake3 {
+ /// Create a new instance of Blake3 with a key
+ pub fn new(key: impl Into<String>) -> Self {
+ Self(key.into())
+ }
+}
+
+impl SignMessage for Blake3 {
+ fn sign_message(
+ &self,
+ secret: &[u8],
+ msg: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::CryptoError> {
+ let key = blake3::derive_key(&self.0, secret);
+ let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec();
+ Ok(output)
+ }
+}
+
+impl VerifySignature for Blake3 {
+ fn verify_signature(
+ &self,
+ secret: &[u8],
+ signature: &[u8],
+ msg: &[u8],
+ ) -> CustomResult<bool, errors::CryptoError> {
+ let key = blake3::derive_key(&self.0, secret);
+ let output = blake3::keyed_hash(&key, msg);
+ Ok(output.as_bytes() == signature)
+ }
+}
+
/// Represents the GCM-AES-256 algorithm
#[derive(Debug)]
pub struct GcmAes256;
diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs
index b2e9124688c..a813829d63d 100644
--- a/crates/masking/src/secret.rs
+++ b/crates/masking/src/secret.rs
@@ -4,7 +4,7 @@
use std::{fmt, marker::PhantomData};
-use crate::{strategy::Strategy, PeekInterface};
+use crate::{strategy::Strategy, PeekInterface, StrongSecret};
///
/// Secret thing.
@@ -81,6 +81,14 @@ where
{
f(self.inner_secret).into()
}
+
+ /// Convert to [`StrongSecret`]
+ pub fn into_strong(self) -> StrongSecret<SecretValue, MaskingStrategy>
+ where
+ SecretValue: zeroize::DefaultIsZeroes,
+ {
+ StrongSecret::new(self.inner_secret)
+ }
}
impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue>
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 54cdb068ec5..69a86a5ed36 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -38,6 +38,11 @@ merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"]
merchant_connector_account_v2 = ["api_models/merchant_connector_account_v2", "kgraph_utils/merchant_connector_account_v2"]
+# Partial Auth
+# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
+# This is named as partial-auth because the router will still try to authenticate if the `x-merchant-id` header is not present.
+partial-auth = []
+
[dependencies]
actix-cors = "0.6.5"
actix-http = "3.6.0"
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs
index d07f08ef407..eeb09b1104a 100644
--- a/crates/router/src/compatibility/stripe/customers.rs
+++ b/crates/router/src/compatibility/stripe/customers.rs
@@ -53,7 +53,7 @@ pub async fn customer_create(
|state, auth, req, _| {
customers::create_customer(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -87,7 +87,7 @@ pub async fn customer_retrieve(
|state, auth, req, _| {
customers::retrieve_customer(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -132,7 +132,7 @@ pub async fn customer_update(
|state, auth, req, _| {
customers::update_customer(state, auth.merchant_account, req, auth.key_store)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -166,7 +166,7 @@ pub async fn customer_delete(
|state, auth: auth::AuthenticationData, req, _| {
customers::delete_customer(state, auth.merchant_account, req, auth.key_store)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -208,7 +208,7 @@ pub async fn list_customer_payment_method_api(
None,
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index fa6b02e499d..c9881647ed9 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -1,4 +1,5 @@
pub mod types;
+
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::payments as payment_types;
use error_stack::report;
@@ -71,7 +72,7 @@ pub async fn payment_intents_create(
api_types::HeaderPayload::default(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
@@ -400,7 +401,7 @@ pub async fn payment_intents_capture(
api_types::HeaderPayload::default(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
@@ -500,7 +501,7 @@ pub async fn payment_intent_list(
|state, auth, req, _| {
payments::list_payments(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs
index 52d5230cfc8..071fdd839eb 100644
--- a/crates/router/src/compatibility/stripe/refunds.rs
+++ b/crates/router/src/compatibility/stripe/refunds.rs
@@ -1,4 +1,5 @@
pub mod types;
+
use actix_web::{web, HttpRequest, HttpResponse};
use error_stack::report;
use router_env::{instrument, tracing, Flow, Tag};
@@ -51,7 +52,7 @@ pub async fn refund_create(
|state, auth, req, _| {
refunds::refund_create_core(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -101,7 +102,7 @@ pub async fn refund_retrieve_with_gateway_creds(
refunds::refund_retrieve_core,
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -143,7 +144,7 @@ pub async fn refund_retrieve(
refunds::refund_retrieve_core,
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -175,7 +176,7 @@ pub async fn refund_update(
&req,
create_refund_update_req,
|state, auth, req, _| refunds::refund_update_core(state, auth.merchant_account, req),
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs
index c7bde0dbcdd..28933e74bfb 100644
--- a/crates/router/src/compatibility/stripe/setup_intents.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents.rs
@@ -1,4 +1,5 @@
pub mod types;
+
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::payments as payment_types;
use error_stack::report;
@@ -72,7 +73,7 @@ pub async fn setup_intents_create(
api_types::HeaderPayload::default(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index c7125770fff..be29da50aed 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -8929,6 +8929,13 @@ impl Default for super::settings::ApiKeys {
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
expiry_reminder_days: vec![7, 3, 1],
+
+ // Hex-encoded key used for calculating checksum for partial auth
+ #[cfg(feature = "partial-auth")]
+ checksum_auth_key: String::new().into(),
+ // context used for blake3
+ #[cfg(feature = "partial-auth")]
+ checksum_auth_context: String::new().into(),
}
}
}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index de53f9c189e..312a475b8ba 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -114,10 +114,24 @@ impl SecretsHandler for settings::ApiKeys {
#[cfg(feature = "email")]
let expiry_reminder_days = api_keys.expiry_reminder_days.clone();
+ #[cfg(feature = "partial-auth")]
+ let checksum_auth_context = secret_management_client
+ .get_secret(api_keys.checksum_auth_context.clone())
+ .await?;
+ #[cfg(feature = "partial-auth")]
+ let checksum_auth_key = secret_management_client
+ .get_secret(api_keys.checksum_auth_key.clone())
+ .await?;
+
Ok(value.transition_state(|_| Self {
hash_key,
#[cfg(feature = "email")]
expiry_reminder_days,
+
+ #[cfg(feature = "partial-auth")]
+ checksum_auth_key,
+ #[cfg(feature = "partial-auth")]
+ checksum_auth_context,
}))
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index a210b86baf1..f42f2218bdd 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -663,6 +663,12 @@ pub struct ApiKeys {
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
pub expiry_reminder_days: Vec<u8>,
+
+ #[cfg(feature = "partial-auth")]
+ pub checksum_auth_context: Secret<String>,
+
+ #[cfg(feature = "partial-auth")]
+ pub checksum_auth_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs
index a2f187eb3ff..7cdfc6e6ea3 100644
--- a/crates/router/src/core/metrics.rs
+++ b/crates/router/src/core/metrics.rs
@@ -84,5 +84,8 @@ counter_metric!(
GLOBAL_METER
);
+#[cfg(feature = "partial-auth")]
+counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER);
+
counter_metric!(API_KEY_REQUEST_INITIATED, GLOBAL_METER);
counter_metric!(API_KEY_REQUEST_COMPLETED, GLOBAL_METER);
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index c9cb9dac908..41ff4502744 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -730,7 +730,7 @@ pub async fn toggle_connector_agnostic_mit(
json_payload.into_inner(),
|state, _, req, _| connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 08d960e6693..8226e6fa420 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -5,6 +5,8 @@ use actix_web::{web, Scope};
use api_models::routing::RoutingRetrieveQuery;
#[cfg(feature = "olap")]
use common_enums::TransactionType;
+#[cfg(feature = "partial-auth")]
+use common_utils::crypto::Blake3;
#[cfg(feature = "email")]
use external_services::email::{ses::AwsSes, EmailService};
use external_services::file_storage::FileStorageInterface;
@@ -56,6 +58,8 @@ use super::{ephemeral_key::*, webhooks::*};
pub use crate::analytics::opensearch::OpenSearchClient;
#[cfg(feature = "olap")]
use crate::analytics::AnalyticsProvider;
+#[cfg(feature = "partial-auth")]
+use crate::errors::RouterResult;
#[cfg(all(feature = "frm", feature = "oltp"))]
use crate::routes::fraud_check as frm_routes;
#[cfg(all(feature = "recon", feature = "olap"))]
@@ -116,6 +120,8 @@ pub trait SessionStateInfo {
fn event_handler(&self) -> EventsHandler;
fn get_request_id(&self) -> Option<String>;
fn add_request_id(&mut self, request_id: RequestId);
+ #[cfg(feature = "partial-auth")]
+ fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>;
fn session_state(&self) -> SessionState;
}
@@ -137,6 +143,39 @@ impl SessionStateInfo for SessionState {
self.store.add_request_id(request_id.to_string());
self.request_id.replace(request_id);
}
+
+ #[cfg(feature = "partial-auth")]
+ fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])> {
+ use error_stack::ResultExt;
+ use hyperswitch_domain_models::errors::api_error_response as errors;
+ use masking::prelude::PeekInterface as _;
+ use router_env::logger;
+
+ let output = CHECKSUM_KEY.get_or_try_init(|| {
+ let conf = self.conf();
+ let context = conf
+ .api_keys
+ .get_inner()
+ .checksum_auth_context
+ .peek()
+ .clone();
+ let key = conf.api_keys.get_inner().checksum_auth_key.peek();
+ hex::decode(key).map(|key| {
+ (
+ masking::StrongSecret::new(context),
+ masking::StrongSecret::new(key),
+ )
+ })
+ });
+
+ match output {
+ Ok((context, key)) => Ok((Blake3::new(context.peek().clone()), key.peek())),
+ Err(err) => {
+ logger::error!("Failed to get checksum key");
+ Err(err).change_context(errors::ApiErrorResponse::InternalServerError)
+ }
+ }
+ }
fn session_state(&self) -> SessionState {
self.clone()
}
@@ -174,6 +213,12 @@ pub trait AppStateInfo {
fn get_request_id(&self) -> Option<String>;
}
+#[cfg(feature = "partial-auth")]
+static CHECKSUM_KEY: once_cell::sync::OnceCell<(
+ masking::StrongSecret<String>,
+ masking::StrongSecret<Vec<u8>>,
+)> = once_cell::sync::OnceCell::new();
+
impl AppStateInfo for AppState {
fn conf(&self) -> settings::Settings<RawSecret> {
self.conf.as_ref().to_owned()
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index bd0ae9f6c66..f2a70a7b905 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -35,7 +35,7 @@ pub async fn add_entry_to_blocklist(
blocklist::add_entry_to_blocklist(state, auth.merchant_account, body)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantAccountWrite),
req.headers(),
),
@@ -71,7 +71,7 @@ pub async fn remove_entry_from_blocklist(
blocklist::remove_entry_from_blocklist(state, auth.merchant_account, body)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantAccountWrite),
req.headers(),
),
@@ -109,7 +109,7 @@ pub async fn list_blocked_payment_methods(
blocklist::list_blocklist_entries(state, auth.merchant_account, query)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantAccountRead),
req.headers(),
),
@@ -147,7 +147,7 @@ pub async fn toggle_blocklist_guard(
blocklist::toggle_blocklist_guard(state, auth.merchant_account, query)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantAccountWrite),
req.headers(),
),
diff --git a/crates/router/src/routes/currency.rs b/crates/router/src/routes/currency.rs
index 15684e6ae88..80b74b5c0c2 100644
--- a/crates/router/src/routes/currency.rs
+++ b/crates/router/src/routes/currency.rs
@@ -16,7 +16,7 @@ pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> Htt
(),
|state, _auth: auth::AuthenticationData, _, _| currency::retrieve_forex(state),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
@@ -48,7 +48,7 @@ pub async fn convert_forex(
)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 0ccf6f9a77b..fe9408dc135 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -26,7 +26,7 @@ pub async fn customers_create(
json_payload.into_inner(),
|state, auth, req, _| create_customer(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::CustomerWrite),
req.headers(),
),
@@ -88,7 +88,7 @@ pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> Htt
)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::CustomerRead),
req.headers(),
),
@@ -115,7 +115,7 @@ pub async fn customers_update(
json_payload.into_inner(),
|state, auth, req, _| update_customer(state, auth.merchant_account, req, auth.key_store),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::CustomerWrite),
req.headers(),
),
@@ -144,7 +144,7 @@ pub async fn customers_delete(
payload,
|state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::CustomerWrite),
req.headers(),
),
@@ -179,7 +179,7 @@ pub async fn get_customer_mandates(
)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MandateRead),
req.headers(),
),
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 4c7199f2f29..1c2377952a1 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -45,7 +45,7 @@ pub async fn retrieve_dispute(
dispute_id,
|state, auth, req, _| disputes::retrieve_dispute(state, auth.merchant_account, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeRead),
req.headers(),
),
@@ -92,7 +92,7 @@ pub async fn retrieve_disputes_list(
payload,
|state, auth, req, _| disputes::retrieve_disputes_list(state, auth.merchant_account, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeRead),
req.headers(),
),
@@ -134,7 +134,7 @@ pub async fn accept_dispute(
disputes::accept_dispute(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeWrite),
req.headers(),
),
@@ -171,7 +171,7 @@ pub async fn submit_dispute_evidence(
disputes::submit_evidence(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeWrite),
req.headers(),
),
@@ -216,7 +216,7 @@ pub async fn attach_dispute_evidence(
disputes::attach_evidence(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeWrite),
req.headers(),
),
@@ -259,7 +259,7 @@ pub async fn retrieve_dispute_evidence(
disputes::retrieve_dispute_evidence(state, auth.merchant_account, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeRead),
req.headers(),
),
@@ -297,7 +297,7 @@ pub async fn delete_dispute_evidence(
json_payload.into_inner(),
|state, auth, req, _| disputes::delete_evidence(state, auth.merchant_account, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::DisputeWrite),
req.headers(),
),
diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs
index 93041bbd0a3..893b2e5a093 100644
--- a/crates/router/src/routes/ephemeral_key.rs
+++ b/crates/router/src/routes/ephemeral_key.rs
@@ -28,7 +28,7 @@ pub async fn ephemeral_key_create(
auth.merchant_account.get_id().to_owned(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
)
.await
@@ -48,7 +48,7 @@ pub async fn ephemeral_key_delete(
&req,
payload,
|state, _, req, _| helpers::delete_ephemeral_key(state, req),
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
)
.await
diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rs
index 92be12b2bc9..028b00a6a6a 100644
--- a/crates/router/src/routes/files.rs
+++ b/crates/router/src/routes/files.rs
@@ -46,7 +46,7 @@ pub async fn files_create(
create_file_request,
|state, auth, req, _| files_create_core(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
@@ -88,7 +88,7 @@ pub async fn files_delete(
file_id,
|state, auth, req, _| files_delete_core(state, auth.merchant_account, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
@@ -132,7 +132,7 @@ pub async fn files_retrieve(
files_retrieve_core(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index c2ed58ae40b..d2c5d5e4644 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -44,7 +44,7 @@ pub async fn get_mandate(
|state, auth, req, _| {
mandate::get_mandate(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -85,7 +85,7 @@ pub async fn revoke_mandate(
|state, auth, req, _| {
mandate::revoke_mandate(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -130,7 +130,7 @@ pub async fn retrieve_mandates_list(
mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MandateRead),
req.headers(),
),
diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs
index b1be7091151..06b1037cb38 100644
--- a/crates/router/src/routes/payment_link.rs
+++ b/crates/router/src/routes/payment_link.rs
@@ -152,7 +152,7 @@ pub async fn payments_link_list(
&req,
payload,
|state, auth, payload, _| list_payment_link(state, auth.merchant_account, payload),
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 05d56c8248f..f55f6c80e7a 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -56,7 +56,7 @@ pub async fn create_payment_method_api(
))
.await
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -426,7 +426,7 @@ pub async fn payment_method_retrieve_api(
|state, auth, pm, _| {
cards::retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -515,7 +515,7 @@ pub async fn list_countries_currencies_for_connector_payment_method(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
req.headers(),
),
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 956909f9e5a..9f6c35cacd8 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -137,9 +137,9 @@ pub async fn payments_create(
)
},
match env::which() {
- env::Env::Production => &auth::ApiKeyAuth,
+ env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PaymentWrite),
req.headers(),
),
@@ -564,7 +564,7 @@ pub async fn payments_capture(
HeaderPayload::default(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
@@ -633,7 +633,7 @@ pub async fn payments_connector_session(
header_payload.clone(),
)
},
- &auth::PublishableKeyAuth,
+ &auth::HeaderAuth(auth::PublishableKeyAuth),
locking_action,
))
.await
@@ -924,7 +924,7 @@ pub async fn payments_cancel(
HeaderPayload::default(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
@@ -972,7 +972,7 @@ pub async fn payments_list(
payments::list_payments(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PaymentRead),
req.headers(),
),
@@ -1088,9 +1088,9 @@ pub async fn payments_approve(
)
},
match env::which() {
- env::Env::Production => &auth::ApiKeyAuth,
+ env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PaymentWrite),
http_req.headers(),
),
@@ -1143,9 +1143,9 @@ pub async fn payments_reject(
)
},
match env::which() {
- env::Env::Production => &auth::ApiKeyAuth,
+ env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PaymentWrite),
http_req.headers(),
),
@@ -1287,7 +1287,7 @@ pub async fn payments_incremental_authorization(
HeaderPayload::default(),
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
@@ -1339,7 +1339,7 @@ pub async fn payments_external_authentication(
req,
)
},
- &auth::PublishableKeyAuth,
+ &auth::HeaderAuth(auth::PublishableKeyAuth),
locking_action,
))
.await
@@ -1456,7 +1456,7 @@ pub async fn retrieve_extended_card_info(
payment_id,
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 4e81b67fb3d..d32aa0da3eb 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -41,7 +41,7 @@ pub async fn payouts_create(
|state, auth, req, _| {
payouts_create_core(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -83,7 +83,7 @@ pub async fn payouts_retrieve(
payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PayoutRead),
req.headers(),
),
@@ -126,7 +126,7 @@ pub async fn payouts_update(
|state, auth, req, _| {
payouts_update_core(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -199,7 +199,7 @@ pub async fn payouts_cancel(
|state, auth, req, _| {
payouts_cancel_core(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -239,7 +239,7 @@ pub async fn payouts_fulfill(
|state, auth, req, _| {
payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -274,7 +274,7 @@ pub async fn payouts_list(
payload,
|state, auth, req, _| payouts_list_core(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PayoutRead),
req.headers(),
),
@@ -314,7 +314,7 @@ pub async fn payouts_list_by_filter(
payouts_filtered_list_core(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PayoutRead),
req.headers(),
),
@@ -354,7 +354,7 @@ pub async fn payouts_list_available_filters(
payouts_list_available_filters_core(state, auth.merchant_account, req)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::PayoutRead),
req.headers(),
),
diff --git a/crates/router/src/routes/poll.rs b/crates/router/src/routes/poll.rs
index e4591b40327..bbb2a9a63a3 100644
--- a/crates/router/src/routes/poll.rs
+++ b/crates/router/src/routes/poll.rs
@@ -39,7 +39,7 @@ pub async fn retrieve_poll_status(
&req,
poll_id,
|state, auth, req, _| poll::retrieve_poll_status(state, req, auth.merchant_account),
- &auth::PublishableKeyAuth,
+ &auth::HeaderAuth(auth::PublishableKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 46ff0dce2ae..013ed064975 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -38,7 +38,7 @@ pub async fn refunds_create(
json_payload.into_inner(),
|state, auth, req, _| refund_create_core(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RefundWrite),
req.headers(),
),
@@ -98,7 +98,7 @@ pub async fn refunds_retrieve(
)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RefundRead),
req.headers(),
),
@@ -148,7 +148,7 @@ pub async fn refunds_retrieve_with_body(
refund_retrieve_core,
)
},
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -188,7 +188,7 @@ pub async fn refunds_update(
&req,
refund_update_req,
|state, auth, req, _| refund_update_core(state, auth.merchant_account, req),
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
@@ -222,7 +222,7 @@ pub async fn refunds_list(
payload.into_inner(),
|state, auth, req, _| refund_list(state, auth.merchant_account, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RefundRead),
req.headers(),
),
@@ -260,7 +260,7 @@ pub async fn refunds_filter_list(
payload.into_inner(),
|state, auth, req, _| refund_filter_list(state, auth.merchant_account, req),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RefundRead),
req.headers(),
),
@@ -293,7 +293,7 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -
(),
|state, auth, _, _| get_filters_for_refunds(state, auth.merchant_account),
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RefundRead),
req.headers(),
),
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 788acd4ba2d..7accfc7f22f 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -2,6 +2,7 @@
//!
//! Functions that are used to perform the api level configuration, retrieval, updation
//! of Routing configs.
+
use actix_web::{web, HttpRequest, Responder};
use api_models::{
enums, routing as routing_types,
@@ -42,7 +43,7 @@ pub async fn routing_create_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
@@ -77,7 +78,7 @@ pub async fn routing_link_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
@@ -107,7 +108,7 @@ pub async fn routing_retrieve_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingRead),
req.headers(),
),
@@ -142,7 +143,7 @@ pub async fn list_routing_configs(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingRead),
req.headers(),
),
@@ -177,7 +178,7 @@ pub async fn routing_unlink_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
@@ -211,7 +212,7 @@ pub async fn routing_update_default_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
@@ -239,7 +240,7 @@ pub async fn routing_retrieve_default_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingRead),
req.headers(),
),
@@ -273,7 +274,7 @@ pub async fn upsert_surcharge_decision_manager_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
req.headers(),
),
@@ -304,7 +305,7 @@ pub async fn delete_surcharge_decision_manager_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
req.headers(),
),
@@ -335,7 +336,7 @@ pub async fn retrieve_surcharge_decision_manager_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
req.headers(),
),
@@ -369,7 +370,7 @@ pub async fn upsert_decision_manager_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
req.headers(),
),
@@ -401,7 +402,7 @@ pub async fn delete_decision_manager_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
req.headers(),
),
@@ -429,7 +430,7 @@ pub async fn retrieve_decision_manager_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
req.headers(),
),
@@ -465,7 +466,7 @@ pub async fn routing_retrieve_linked_config(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingRead),
req.headers(),
),
@@ -497,13 +498,13 @@ pub async fn routing_retrieve_default_config_for_profiles(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingRead),
req.headers(),
),
#[cfg(feature = "release")]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingRead),
req.headers(),
),
@@ -541,7 +542,7 @@ pub async fn routing_update_default_config_for_profile(
},
#[cfg(not(feature = "release"))]
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::RoutingWrite),
req.headers(),
),
diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs
index 25e64e95bde..41993408791 100644
--- a/crates/router/src/routes/verification.rs
+++ b/crates/router/src/routes/verification.rs
@@ -30,7 +30,7 @@ pub async fn apple_pay_merchant_registration(
)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantAccountWrite),
req.headers(),
),
@@ -62,7 +62,7 @@ pub async fn retrieve_apple_pay_verified_domains(
)
},
auth::auth_type(
- &auth::ApiKeyAuth,
+ &auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth(Permission::MerchantAccountRead),
req.headers(),
),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 0ee09913e2b..df59083537f 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -15,6 +15,8 @@ use router_env::logger;
use serde::Serialize;
use self::blacklist::BlackList;
+#[cfg(feature = "partial-auth")]
+use self::detached::{ExtractedPayload, GetAuthType};
use super::authorization::{self, permissions::Permission};
#[cfg(feature = "olap")]
use super::jwt;
@@ -26,6 +28,8 @@ use crate::configs::Settings;
use crate::consts;
#[cfg(feature = "olap")]
use crate::core::errors::UserResult;
+#[cfg(feature = "partial-auth")]
+use crate::core::metrics;
#[cfg(feature = "recon")]
use crate::routes::SessionState;
use crate::{
@@ -38,10 +42,14 @@ use crate::{
types::domain,
utils::OptionExt,
};
+
pub mod blacklist;
pub mod cookies;
pub mod decision;
+#[cfg(feature = "partial-auth")]
+mod detached;
+
#[derive(Clone, Debug)]
pub struct AuthenticationData {
pub merchant_account: domain::MerchantAccount,
@@ -248,6 +256,29 @@ pub struct ApiKeyAuth;
pub struct NoAuth;
+#[cfg(feature = "partial-auth")]
+impl GetAuthType for ApiKeyAuth {
+ fn get_auth_type(&self) -> detached::PayloadType {
+ detached::PayloadType::ApiKey
+ }
+}
+
+//
+// # Header Auth
+//
+// Header Auth is a feature that allows you to authenticate requests using custom headers. This is
+// done by checking whether the request contains the specified headers.
+// - `x-merchant-id` header is used to authenticate the merchant.
+//
+// ## Checksum
+// - `x-auth-checksum` header is used to authenticate the request. The checksum is calculated using the
+// above mentioned headers is generated by hashing the headers mentioned above concatenated with `:` and then hashed with the detached authentication key.
+//
+// When the [`partial-auth`] feature is disabled the implementation for [`AuthenticateAndFetch`]
+// changes where the authentication is done by the [`I`] implementation.
+//
+pub struct HeaderAuth<I>(pub I);
+
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for NoAuth
where
@@ -356,6 +387,136 @@ where
}
}
+#[cfg(not(feature = "partial-auth"))]
+#[async_trait]
+impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
+where
+ A: SessionStateInfo + Send + Sync,
+ I: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ self.0.authenticate_and_fetch(request_headers, state).await
+ }
+}
+
+#[cfg(feature = "partial-auth")]
+#[async_trait]
+impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
+where
+ A: SessionStateInfo + Sync,
+ I: AuthenticateAndFetch<AuthenticationData, A> + GetAuthType + Sync + Send,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let report_failure = || {
+ metrics::PARTIAL_AUTH_FAILURE.add(&metrics::CONTEXT, 1, &[]);
+ };
+
+ let payload = ExtractedPayload::from_headers(request_headers)
+ .and_then(|value| {
+ let (algo, secret) = state.get_detached_auth()?;
+
+ Ok(value
+ .verify_checksum(request_headers, algo, secret)
+ .then_some(value))
+ })
+ .map(|inner_payload| {
+ inner_payload.and_then(|inner| {
+ (inner.payload_type == self.0.get_auth_type()).then_some(inner)
+ })
+ });
+
+ match payload {
+ Ok(Some(data)) => match data {
+ ExtractedPayload {
+ payload_type: detached::PayloadType::ApiKey,
+ merchant_id: Some(merchant_id),
+ key_id: Some(key_id),
+ } => {
+ let auth = construct_authentication_data(state, &merchant_id).await?;
+ Ok((
+ auth.clone(),
+ AuthenticationType::ApiKey {
+ merchant_id: auth.merchant_account.get_id().clone(),
+ key_id,
+ },
+ ))
+ }
+ ExtractedPayload {
+ payload_type: detached::PayloadType::PublishableKey,
+ merchant_id: Some(merchant_id),
+ key_id: None,
+ } => {
+ let auth = construct_authentication_data(state, &merchant_id).await?;
+ Ok((
+ auth.clone(),
+ AuthenticationType::PublishableKey {
+ merchant_id: auth.merchant_account.get_id().clone(),
+ },
+ ))
+ }
+ _ => {
+ report_failure();
+ self.0.authenticate_and_fetch(request_headers, state).await
+ }
+ },
+ Ok(None) => {
+ report_failure();
+ self.0.authenticate_and_fetch(request_headers, state).await
+ }
+ Err(error) => {
+ logger::error!(%error, "Failed to extract payload from headers");
+ report_failure();
+ self.0.authenticate_and_fetch(request_headers, state).await
+ }
+ }
+ }
+}
+
+#[cfg(feature = "partial-auth")]
+async fn construct_authentication_data<A>(
+ state: &A,
+ merchant_id: &id_type::MerchantId,
+) -> RouterResult<AuthenticationData>
+where
+ A: SessionStateInfo,
+{
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ &(&state.session_state()).into(),
+ merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(
+ &(&state.session_state()).into(),
+ merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ };
+
+ Ok(auth)
+}
+
#[cfg(feature = "olap")]
#[derive(Debug)]
pub(crate) struct SinglePurposeJWTAuth(pub TokenPurpose);
@@ -587,6 +748,13 @@ where
#[derive(Debug)]
pub struct PublishableKeyAuth;
+#[cfg(feature = "partial-auth")]
+impl GetAuthType for PublishableKeyAuth {
+ fn get_auth_type(&self) -> detached::PayloadType {
+ detached::PayloadType::PublishableKey
+ }
+}
+
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth
where
@@ -1082,7 +1250,7 @@ impl ClientSecretFetch for api_models::payment_methods::PaymentMethodUpdate {
}
}
-pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync>(
+pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, A>>,
@@ -1091,9 +1259,12 @@ pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync>(
let api_key = get_api_key(headers)?;
if api_key.starts_with("pk_") {
- return Ok((Box::new(PublishableKeyAuth), api::AuthFlow::Client));
+ return Ok((
+ Box::new(HeaderAuth(PublishableKeyAuth)),
+ api::AuthFlow::Client,
+ ));
}
- Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant))
+ Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant))
}
pub fn check_client_secret_and_get_auth<T>(
@@ -1104,7 +1275,7 @@ pub fn check_client_secret_and_get_auth<T>(
api::AuthFlow,
)>
where
- T: SessionStateInfo,
+ T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
@@ -1116,7 +1287,10 @@ where
.map_err(|_| errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
- return Ok((Box::new(PublishableKeyAuth), api::AuthFlow::Client));
+ return Ok((
+ Box::new(HeaderAuth(PublishableKeyAuth)),
+ api::AuthFlow::Client,
+ ));
}
if payload.get_client_secret().is_some() {
@@ -1125,7 +1299,7 @@ where
}
.into());
}
- Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant))
+ Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant))
}
pub async fn get_ephemeral_or_other_auth<T>(
@@ -1138,7 +1312,7 @@ pub async fn get_ephemeral_or_other_auth<T>(
bool,
)>
where
- T: SessionStateInfo,
+ T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
@@ -1148,7 +1322,11 @@ where
if api_key.starts_with("epk") {
Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true))
} else if is_merchant_flow {
- Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant, false))
+ Ok((
+ Box::new(HeaderAuth(ApiKeyAuth)),
+ api::AuthFlow::Merchant,
+ false,
+ ))
} else {
let payload = payload.get_required_value("ClientSecretFetch")?;
let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?;
@@ -1156,13 +1334,13 @@ where
}
}
-pub fn is_ephemeral_auth<A: SessionStateInfo + Sync>(
+pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> {
let api_key = get_api_key(headers)?;
if !api_key.starts_with("epk") {
- Ok(Box::new(ApiKeyAuth))
+ Ok(Box::new(HeaderAuth(ApiKeyAuth)))
} else {
Ok(Box::new(EphemeralKeyAuth))
}
diff --git a/crates/router/src/services/authentication/detached.rs b/crates/router/src/services/authentication/detached.rs
new file mode 100644
index 00000000000..af373d3e559
--- /dev/null
+++ b/crates/router/src/services/authentication/detached.rs
@@ -0,0 +1,109 @@
+use std::{borrow::Cow, string::ToString};
+
+use actix_web::http::header::HeaderMap;
+use common_utils::{crypto::VerifySignature, id_type::MerchantId};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
+
+use crate::core::errors::RouterResult;
+
+const HEADER_AUTH_TYPE: &str = "x-auth-type";
+const HEADER_MERCHANT_ID: &str = "x-merchant-id";
+const HEADER_KEY_ID: &str = "x-key-id";
+const HEADER_CHECKSUM: &str = "x-checksum";
+
+#[derive(Debug)]
+pub struct ExtractedPayload {
+ pub payload_type: PayloadType,
+ pub merchant_id: Option<MerchantId>,
+ pub key_id: Option<String>,
+}
+
+#[derive(strum::EnumString, strum::Display, PartialEq, Debug)]
+#[strum(serialize_all = "snake_case")]
+pub enum PayloadType {
+ ApiKey,
+ PublishableKey,
+}
+
+pub trait GetAuthType {
+ fn get_auth_type(&self) -> PayloadType;
+}
+
+impl ExtractedPayload {
+ pub fn from_headers(headers: &HeaderMap) -> RouterResult<Self> {
+ let merchant_id = headers
+ .get(HEADER_MERCHANT_ID)
+ .and_then(|value| value.to_str().ok())
+ .ok_or_else(|| ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header is invalid or not present", HEADER_MERCHANT_ID),
+ })
+ .map_err(error_stack::Report::from)
+ .and_then(|merchant_id| {
+ MerchantId::try_from(Cow::from(merchant_id.to_string())).change_context(
+ ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "`{}` header is invalid or not present",
+ HEADER_MERCHANT_ID
+ ),
+ },
+ )
+ })?;
+
+ let auth_type: PayloadType = headers
+ .get(HEADER_AUTH_TYPE)
+ .and_then(|inner| inner.to_str().ok())
+ .ok_or_else(|| ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header not present", HEADER_AUTH_TYPE),
+ })?
+ .parse::<PayloadType>()
+ .change_context(ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header not present", HEADER_AUTH_TYPE),
+ })?;
+
+ Ok(Self {
+ payload_type: auth_type,
+ merchant_id: Some(merchant_id),
+ key_id: headers
+ .get(HEADER_KEY_ID)
+ .and_then(|v| v.to_str().ok())
+ .map(|v| v.to_string()),
+ })
+ }
+
+ pub fn verify_checksum(
+ &self,
+ headers: &HeaderMap,
+ algo: impl VerifySignature,
+ secret: &[u8],
+ ) -> bool {
+ let output = || {
+ let checksum = headers.get(HEADER_CHECKSUM)?.to_str().ok()?;
+ let payload = self.generate_payload();
+
+ algo.verify_signature(secret, &hex::decode(checksum).ok()?, payload.as_bytes())
+ .ok()
+ };
+
+ output().unwrap_or(false)
+ }
+
+ // The payload should be `:` separated strings of all the fields
+ fn generate_payload(&self) -> String {
+ append_option(
+ &self.payload_type.to_string(),
+ &self
+ .merchant_id
+ .as_ref()
+ .map(|inner| append_option(inner.get_string_repr(), &self.key_id)),
+ )
+ }
+}
+
+#[inline]
+fn append_option(prefix: &str, data: &Option<String>) -> String {
+ match data {
+ Some(inner) => format!("{}:{}", prefix, inner),
+ None => prefix.to_string(),
+ }
+}
|
feat
|
Add support for partial-auth, by facilitating injection of authentication parameters in headers (#4802)
|
1dc660f80453306e86a3ea77d09829118100b59b
|
2024-02-12 13:47:09
|
Sai Harsha Vardhan
|
feat(router): add `delete_evidence` api for disputes (#3608)
| false
|
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index ca701ddf9b3..e4c38cef860 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -79,7 +79,7 @@ pub struct DisputeResponsePaymentsRetrieve {
pub created_at: PrimitiveDateTime,
}
-#[derive(Debug, Serialize, strum::Display, Clone)]
+#[derive(Debug, Serialize, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EvidenceType {
@@ -196,3 +196,11 @@ pub struct SubmitEvidenceRequest {
/// Any additional evidence statements
pub uncategorized_text: Option<String>,
}
+
+#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
+pub struct DeleteEvidenceRequest {
+ /// Id of the dispute
+ pub dispute_id: String,
+ /// Evidence Type to be deleted
+ pub evidence_type: EvidenceType,
+}
diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs
index 101dba3ca02..1ea6f4e8552 100644
--- a/crates/api_models/src/events/dispute.rs
+++ b/crates/api_models/src/events/dispute.rs
@@ -1,6 +1,8 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
-use super::{DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest};
+use super::{
+ DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest,
+};
impl ApiEventMetric for SubmitEvidenceRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -23,3 +25,10 @@ impl ApiEventMetric for DisputeResponse {
})
}
}
+impl ApiEventMetric for DeleteEvidenceRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Dispute {
+ dispute_id: self.dispute_id.clone(),
+ })
+ }
+}
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 535d004e902..285baa33d1a 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -423,3 +423,43 @@ pub async fn retrieve_dispute_evidence(
transformers::get_dispute_evidence_vec(&state, merchant_account, dispute_evidence).await?;
Ok(services::ApplicationResponse::Json(dispute_evidence_vec))
}
+
+pub async fn delete_evidence(
+ state: AppState,
+ merchant_account: domain::MerchantAccount,
+ delete_evidence_request: dispute_models::DeleteEvidenceRequest,
+) -> RouterResponse<serde_json::Value> {
+ let dispute_id = delete_evidence_request.dispute_id.clone();
+ let dispute = state
+ .store
+ .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &dispute_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
+ dispute_id: dispute_id.clone(),
+ })?;
+ let dispute_evidence: api::DisputeEvidence = dispute
+ .evidence
+ .clone()
+ .parse_value("DisputeEvidence")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while parsing dispute evidence record")?;
+ let updated_dispute_evidence =
+ transformers::delete_evidence_file(dispute_evidence, delete_evidence_request.evidence_type);
+ let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate {
+ evidence: utils::Encode::<api::DisputeEvidence>::encode_to_value(&updated_dispute_evidence)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while encoding dispute evidence")?
+ .into(),
+ };
+ state
+ .store
+ .update_dispute(dispute, update_dispute)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
+ dispute_id: dispute_id.to_owned(),
+ })
+ .attach_printable_lazy(|| {
+ format!("Unable to update dispute with dispute_id: {dispute_id}")
+ })?;
+ Ok(services::ApplicationResponse::StatusOk)
+}
diff --git a/crates/router/src/core/disputes/transformers.rs b/crates/router/src/core/disputes/transformers.rs
index 8fb4f41e98a..936184fc993 100644
--- a/crates/router/src/core/disputes/transformers.rs
+++ b/crates/router/src/core/disputes/transformers.rs
@@ -222,6 +222,54 @@ pub async fn get_dispute_evidence_block(
})
}
+pub fn delete_evidence_file(
+ dispute_evidence: DisputeEvidence,
+ evidence_type: EvidenceType,
+) -> DisputeEvidence {
+ match evidence_type {
+ EvidenceType::CancellationPolicy => DisputeEvidence {
+ cancellation_policy: None,
+ ..dispute_evidence
+ },
+ EvidenceType::CustomerCommunication => DisputeEvidence {
+ customer_communication: None,
+ ..dispute_evidence
+ },
+ EvidenceType::CustomerSignature => DisputeEvidence {
+ customer_signature: None,
+ ..dispute_evidence
+ },
+ EvidenceType::Receipt => DisputeEvidence {
+ receipt: None,
+ ..dispute_evidence
+ },
+ EvidenceType::RefundPolicy => DisputeEvidence {
+ refund_policy: None,
+ ..dispute_evidence
+ },
+ EvidenceType::ServiceDocumentation => DisputeEvidence {
+ service_documentation: None,
+ ..dispute_evidence
+ },
+ EvidenceType::ShippingDocumentation => DisputeEvidence {
+ shipping_documentation: None,
+ ..dispute_evidence
+ },
+ EvidenceType::InvoiceShowingDistinctTransactions => DisputeEvidence {
+ invoice_showing_distinct_transactions: None,
+ ..dispute_evidence
+ },
+ EvidenceType::RecurringTransactionAgreement => DisputeEvidence {
+ recurring_transaction_agreement: None,
+ ..dispute_evidence
+ },
+ EvidenceType::UncategorizedFile => DisputeEvidence {
+ uncategorized_file: None,
+ ..dispute_evidence
+ },
+ }
+}
+
pub async fn get_dispute_evidence_vec(
state: &AppState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 5fbb4b3affc..1a8a2d696b1 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -848,7 +848,8 @@ impl Disputes {
.service(
web::resource("/evidence")
.route(web::post().to(submit_dispute_evidence))
- .route(web::put().to(attach_dispute_evidence)),
+ .route(web::put().to(attach_dispute_evidence))
+ .route(web::delete().to(delete_dispute_evidence)),
)
.service(
web::resource("/evidence/{dispute_id}")
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 7bcd8ad3512..60f6dd74186 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -264,3 +264,41 @@ pub async fn retrieve_dispute_evidence(
))
.await
}
+
+/// Disputes - Delete Evidence attached to a Dispute
+///
+/// To delete an evidence file attached to a dispute
+#[utoipa::path(
+ put,
+ path = "/disputes/evidence",
+ request_body=DeleteEvidenceRequest,
+ responses(
+ (status = 200, description = "Evidence deleted from a dispute"),
+ (status = 400, description = "Bad Request")
+ ),
+ tag = "Disputes",
+ operation_id = "Delete Evidence attached to a Dispute",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::DeleteDisputeEvidence))]
+pub async fn delete_dispute_evidence(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<dispute_models::DeleteEvidenceRequest>,
+) -> HttpResponse {
+ let flow = Flow::DeleteDisputeEvidence;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth, req| disputes::delete_evidence(state, auth.merchant_account, req),
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::DisputeWrite),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 02a45408baf..9393e8ae212 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::DisputesList
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
- | Flow::RetrieveDisputeEvidence => Self::Disputes,
+ | Flow::RetrieveDisputeEvidence
+ | Flow::DeleteDisputeEvidence => Self::Disputes,
Flow::CardsInfo => Self::CardsInfo,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 2f4d48bea74..6649b89911a 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -235,6 +235,8 @@ pub enum Flow {
CreateConfigKey,
/// Attach Dispute Evidence flow
AttachDisputeEvidence,
+ /// Delete Dispute Evidence flow
+ DeleteDisputeEvidence,
/// Retrieve Dispute Evidence flow
RetrieveDisputeEvidence,
/// Invalidate cache flow
|
feat
|
add `delete_evidence` api for disputes (#3608)
|
22743ac37009e11b7518c5ab013e88360c658c34
|
2024-08-22 15:56:15
|
Amisha Prabhat
|
refactor(core): Refactor fallback routing behaviour in payments for v2 (#5642)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index cf7718d8875..0a0448cae47 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -454,6 +454,7 @@ dependencies = [
"nutype",
"reqwest",
"router_derive",
+ "rustc-hash",
"serde",
"serde_json",
"strum 0.26.2",
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index e342fb3db91..0134c6c6fc9 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -39,6 +39,7 @@ strum = { version = "0.26", features = ["derive"] }
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"] }
+rustc-hash = "1.1.0"
nutype = { version = "0.4.2", features = ["serde"] }
# First party crates
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index c4261d624f1..1f890b1bf89 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -5,8 +5,8 @@ use common_utils::{
pii::{self, EmailStrategy},
types::{keymanager::ToEncryptable, Description},
};
-use euclid::dssa::graph::euclid_graph_prelude::FxHashMap;
use masking::{ExposeInterface, Secret, SwitchStrategy};
+use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index e303fbc9792..e5b0d4cad0b 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -15,9 +15,9 @@ use common_utils::{
types::{keymanager::ToEncryptable, MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
-use euclid::dssa::graph::euclid_graph_prelude::FxHashMap;
use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy, WithType};
use router_derive::Setter;
+use rustc_hash::FxHashMap;
use serde::{
de::{self, Unexpected, Visitor},
ser::Serializer,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index ca1b24a06fb..2a3ce4880e5 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -7,7 +7,7 @@ use api_models::{
use base64::Engine;
use common_utils::{
date_time,
- ext_traits::{AsyncExt, Encode, ValueExt},
+ ext_traits::{AsyncExt, Encode, OptionExt, ValueExt},
id_type, pii, type_name,
types::keymanager::{self as km_types, KeyManagerState},
};
@@ -21,12 +21,6 @@ use regex::Regex;
use router_env::metrics::add_attributes;
use uuid::Uuid;
-#[cfg(all(
- feature = "v2",
- feature = "routing_v2",
- feature = "business_profile_v2"
-))]
-use crate::core::routing;
#[cfg(any(feature = "v1", feature = "v2"))]
use crate::types::transformers::ForeignFrom;
use crate::{
@@ -37,8 +31,7 @@ use crate::{
payment_methods::{cards, transformers},
payments::helpers,
pm_auth::helpers::PaymentAuthConnectorDataExt,
- routing::helpers as routing_helpers,
- utils as core_utils,
+ routing, utils as core_utils,
},
db::StorageInterface,
routes::{metrics, SessionState},
@@ -55,6 +48,7 @@ use crate::{
},
utils,
};
+
const IBAN_MAX_LENGTH: usize = 34;
const BACS_SORT_CODE_LENGTH: usize = 6;
const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8;
@@ -1871,23 +1865,40 @@ impl<'a> ConnectorTypeAndConnectorName<'a> {
Ok(routable_connector)
}
}
-
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2",))
+))]
struct MerchantDefaultConfigUpdate<'a> {
routable_connector: &'a Option<api_enums::RoutableConnectors>,
merchant_connector_id: &'a String,
store: &'a dyn StorageInterface,
merchant_id: &'a id_type::MerchantId,
- default_routing_config: &'a Vec<api_models::routing::RoutableConnectorChoice>,
- default_routing_config_for_profile: &'a Vec<api_models::routing::RoutableConnectorChoice>,
profile_id: &'a String,
transaction_type: &'a api_enums::TransactionType,
}
-
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2",))
+))]
impl<'a> MerchantDefaultConfigUpdate<'a> {
- async fn update_merchant_default_config(&self) -> RouterResult<()> {
- let mut default_routing_config = self.default_routing_config.to_owned();
- let mut default_routing_config_for_profile =
- self.default_routing_config_for_profile.to_owned();
+ async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists(
+ &self,
+ ) -> RouterResult<()> {
+ let mut default_routing_config = routing::helpers::get_merchant_default_config(
+ self.store,
+ self.merchant_id.get_string_repr(),
+ self.transaction_type,
+ )
+ .await?;
+
+ let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(
+ self.store,
+ self.profile_id,
+ self.transaction_type,
+ )
+ .await?;
+
if let Some(routable_connector_val) = self.routable_connector {
let choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
@@ -1896,7 +1907,7 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
};
if !default_routing_config.contains(&choice) {
default_routing_config.push(choice.clone());
- routing_helpers::update_merchant_default_config(
+ routing::helpers::update_merchant_default_config(
self.store,
self.merchant_id.get_string_repr(),
default_routing_config.clone(),
@@ -1906,7 +1917,7 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
}
if !default_routing_config_for_profile.contains(&choice.clone()) {
default_routing_config_for_profile.push(choice);
- routing_helpers::update_merchant_default_config(
+ routing::helpers::update_merchant_default_config(
self.store,
self.profile_id,
default_routing_config_for_profile.clone(),
@@ -1918,7 +1929,53 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
Ok(())
}
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2",
+))]
+struct DefaultFallbackRoutingConfigUpdate<'a> {
+ routable_connector: &'a Option<api_enums::RoutableConnectors>,
+ merchant_connector_id: &'a String,
+ store: &'a dyn StorageInterface,
+ business_profile: domain::BusinessProfile,
+ key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
+ key_manager_state: &'a KeyManagerState,
+}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+impl<'a> DefaultFallbackRoutingConfigUpdate<'a> {
+ async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists(
+ &self,
+ ) -> RouterResult<()> {
+ let profile_wrapper = BusinessProfileWrapper::new(self.business_profile.clone());
+ let default_routing_config_for_profile =
+ &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
+ if let Some(routable_connector_val) = self.routable_connector {
+ let choice = routing_types::RoutableConnectorChoice {
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: *routable_connector_val,
+ merchant_connector_id: Some(self.merchant_connector_id.clone()),
+ };
+ if !default_routing_config_for_profile.contains(&choice.clone()) {
+ default_routing_config_for_profile.push(choice);
+ profile_wrapper
+ .update_default_fallback_routing_of_connectors_under_profile(
+ self.store,
+ &default_routing_config_for_profile,
+ self.key_manager_state,
+ &self.key_store,
+ )
+ .await?
+ }
+ }
+ Ok(())
+ }
+}
#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
trait MerchantConnectorAccountUpdateBridge {
@@ -2219,14 +2276,13 @@ trait MerchantConnectorAccountCreateBridge {
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount>;
- async fn validate_and_get_profile_id(
+ async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- should_validate: bool,
- ) -> RouterResult<String>;
+ ) -> RouterResult<domain::BusinessProfile>;
}
#[cfg(all(
@@ -2360,27 +2416,28 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
})
}
- async fn validate_and_get_profile_id(
+ async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- should_validate: bool,
- ) -> RouterResult<String> {
+ ) -> RouterResult<domain::BusinessProfile> {
let profile_id = self.profile_id;
// Check whether this business profile belongs to the merchant
- if should_validate {
- let _ = core_utils::validate_and_get_business_profile(
- db,
- key_manager_state,
- key_store,
- Some(&profile_id),
- merchant_account.get_id(),
- )
- .await?;
- }
- Ok(profile_id.clone())
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })?;
+
+ Ok(business_profile)
}
}
@@ -2533,28 +2590,31 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
/// If profile_id is not passed, use default profile if available, or
/// If business_details (business_country and business_label) are passed, get the business_profile
/// or return a `MissingRequiredField` error
- async fn validate_and_get_profile_id(
+ async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- should_validate: bool,
- ) -> RouterResult<String> {
+ ) -> RouterResult<domain::BusinessProfile> {
match self.profile_id.or(merchant_account.default_profile.clone()) {
Some(profile_id) => {
// Check whether this business profile belongs to the merchant
- if should_validate {
- let _ = core_utils::validate_and_get_business_profile(
- db,
- key_manager_state,
- key_store,
- Some(&profile_id),
- merchant_account.get_id(),
- )
- .await?;
- }
- Ok(profile_id.clone())
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(
+ errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id },
+ )?;
+
+ Ok(business_profile)
}
None => match self.business_country.zip(self.business_label) {
Some((business_country, business_label)) => {
@@ -2571,7 +2631,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_name },
)?;
- Ok(business_profile.profile_id)
+ Ok(business_profile)
}
_ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id or business_country, business_label"
@@ -2627,15 +2687,9 @@ pub async fn create_connector(
&merchant_account,
)?;
- let profile_id = req
+ let business_profile = req
.clone()
- .validate_and_get_profile_id(
- &merchant_account,
- store,
- key_manager_state,
- &key_store,
- true,
- )
+ .validate_and_get_business_profile(&merchant_account, store, key_manager_state, &key_store)
.await?;
let pm_auth_config_validation = PMAuthConfigValidation {
@@ -2643,20 +2697,12 @@ pub async fn create_connector(
pm_auth_config: &req.pm_auth_config,
db: store,
merchant_id,
- profile_id: &profile_id.clone(),
+ profile_id: &business_profile.profile_id,
key_store: &key_store,
key_manager_state,
};
pm_auth_config_validation.validate_pm_auth_config().await?;
- let business_profile = state
- .store
- .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
- id: profile_id.to_owned(),
- })?;
-
let connector_type_and_connector_enum = ConnectorTypeAndConnectorName {
connector_type: &req.connector_type,
connector_name: &req.connector_name,
@@ -2687,22 +2733,6 @@ pub async fn create_connector(
)
.await?;
- let transaction_type = req.get_transaction_type();
-
- let mut default_routing_config = routing_helpers::get_merchant_default_config(
- &*state.store,
- merchant_id.get_string_repr(),
- &transaction_type,
- )
- .await?;
-
- let mut default_routing_config_for_profile = routing_helpers::get_merchant_default_config(
- &*state.clone().store,
- &profile_id,
- &transaction_type,
- )
- .await?;
-
let mca = state
.store
.insert_merchant_connector_account(
@@ -2713,27 +2743,44 @@ pub async fn create_connector(
.await
.to_duplicate_response(
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
- profile_id: profile_id.clone(),
+ profile_id: business_profile.profile_id.clone(),
connector_label: merchant_connector_account
.connector_label
.unwrap_or_default(),
},
)?;
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2",))
+ ))]
//update merchant default config
let merchant_default_config_update = MerchantDefaultConfigUpdate {
routable_connector: &routable_connector,
merchant_connector_id: &mca.get_id(),
store,
merchant_id,
- default_routing_config: &mut default_routing_config,
- default_routing_config_for_profile: &mut default_routing_config_for_profile,
- profile_id: &profile_id,
- transaction_type: &transaction_type,
+ profile_id: &business_profile.profile_id,
+ transaction_type: &req.get_transaction_type(),
+ };
+
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2",
+ ))]
+ //update merchant default config
+ let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate {
+ routable_connector: &routable_connector,
+ merchant_connector_id: &mca.get_id(),
+ store,
+ business_profile,
+ key_store,
+ key_manager_state,
};
merchant_default_config_update
- .update_merchant_default_config()
+ .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
metrics::MCA_CREATE.add(
@@ -4033,31 +4080,23 @@ impl BusinessProfileWrapper {
Ok(())
}
- pub fn get_profile_id_and_routing_algorithm_id<F>(
- &self,
- transaction_data: &routing::TransactionData<'_, F>,
- ) -> (Option<String>, Option<String>)
+ pub fn get_routing_algorithm_id<'a, F>(
+ &'a self,
+ transaction_data: &'a routing::TransactionData<'_, F>,
+ ) -> Option<String>
where
F: Send + Clone,
{
match transaction_data {
- routing::TransactionData::Payment(payment_data) => (
- payment_data.payment_intent.profile_id.clone(),
- self.profile.routing_algorithm_id.clone(),
- ),
+ routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(),
#[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => (
- Some(payout_data.payout_attempt.profile_id.clone()),
- self.profile.payout_routing_algorithm_id.clone(),
- ),
+ routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(),
}
}
pub fn get_default_fallback_list_of_connector_under_profile(
&self,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
- use common_utils::ext_traits::OptionExt;
use masking::ExposeOptionInterface;
-
self.profile
.default_fallback_routing
.clone()
@@ -4080,7 +4119,7 @@ impl BusinessProfileWrapper {
})
}
- pub async fn update_default_routing_for_profile(
+ pub async fn update_default_fallback_routing_of_connectors_under_profile(
self,
db: &dyn StorageInterface,
updated_config: &Vec<routing_types::RoutableConnectorChoice>,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 3ce9c9ab5af..402e5b4b0a1 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2435,10 +2435,17 @@ pub async fn list_payment_methods(
)
.await?;
+ let profile_id = profile_id
+ .clone()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Profile id not found".to_string(),
+ })?;
+
// filter out payment connectors based on profile_id
let filtered_mcas = helpers::filter_mca_based_on_profile_and_connector_type(
all_mcas.clone(),
- profile_id.as_ref(),
+ &profile_id,
ConnectorType::PaymentProcessor,
);
@@ -2447,12 +2454,6 @@ pub async fn list_payment_methods(
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
// Key creation for storing PM_FILTER_CGRAPH
let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::GenericNotFoundError {
- message: "Profile id not found".to_string(),
- })?;
format!(
"pm_filters_cgraph_{}_{}",
merchant_account.get_id().get_string_repr(),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 287e144f396..6938d3c407b 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3523,6 +3523,7 @@ where
.merchant_connector_id
.clone()
.as_ref(),
+ business_profile.clone(),
)
.await?;
@@ -3555,15 +3556,13 @@ where
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
- let profile_id = payment_data.payment_intent.profile_id.clone();
-
connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
key_store,
connectors,
&TransactionData::Payment(payment_data),
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3604,15 +3603,13 @@ where
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
- let profile_id = payment_data.payment_intent.profile_id.clone();
-
connectors = routing::perform_eligibility_analysis_with_fallback(
&state,
key_store,
connectors,
&TransactionData::Payment(payment_data),
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3978,6 +3975,7 @@ where
feature = "routing_v2",
feature = "business_profile_v2"
))]
+#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v1<F>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
@@ -3991,14 +3989,14 @@ pub async fn route_connector_v1<F>(
where
F: Send + Clone,
{
- let (profile_id, routing_algorithm_id) =
- super::admin::BusinessProfileWrapper::new(business_profile.clone())
- .get_profile_id_and_routing_algorithm_id(&transaction_data);
+ let profile_wrapper = super::admin::BusinessProfileWrapper::new(business_profile.clone());
+ let routing_algorithm_id = profile_wrapper.get_routing_algorithm_id(&transaction_data);
let connectors = routing::perform_static_routing_v1(
state,
merchant_account.get_id(),
routing_algorithm_id,
+ business_profile,
&transaction_data,
)
.await
@@ -4010,7 +4008,7 @@ where
connectors,
&transaction_data,
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -4079,17 +4077,12 @@ pub async fn route_connector_v1<F>(
where
F: Send + Clone,
{
- let (profile_id, routing_algorithm_id) = {
- let (profile_id, routing_algorithm) = match &transaction_data {
- TransactionData::Payment(payment_data) => (
- payment_data.payment_intent.profile_id.clone(),
- business_profile.routing_algorithm.clone(),
- ),
+ let routing_algorithm_id = {
+ let routing_algorithm = match &transaction_data {
+ TransactionData::Payment(_) => business_profile.routing_algorithm.clone(),
+
#[cfg(feature = "payouts")]
- TransactionData::Payout(payout_data) => (
- Some(payout_data.payout_attempt.profile_id.clone()),
- business_profile.payout_routing_algorithm.clone(),
- ),
+ TransactionData::Payout(_) => business_profile.payout_routing_algorithm.clone(),
};
let algorithm_ref = routing_algorithm
@@ -4098,13 +4091,14 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode merchant routing algorithm ref")?
.unwrap_or_default();
- (profile_id, algorithm_ref.algorithm_id)
+ algorithm_ref.algorithm_id
};
let connectors = routing::perform_static_routing_v1(
state,
merchant_account.get_id(),
routing_algorithm_id,
+ business_profile,
&transaction_data,
)
.await
@@ -4115,7 +4109,7 @@ where
connectors,
&transaction_data,
eligible_connectors,
- profile_id,
+ business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 2e7727bbe08..ed30a7ff49b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -45,6 +45,12 @@ use super::{
operations::{BoxedOperation, Operation, PaymentResponse},
CustomerDetails, PaymentData,
};
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+use crate::core::admin as core_admin;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
@@ -124,15 +130,12 @@ pub fn create_certificate(
pub fn filter_mca_based_on_profile_and_connector_type(
merchant_connector_accounts: Vec<domain::MerchantConnectorAccount>,
- profile_id: Option<&String>,
+ profile_id: &String,
connector_type: ConnectorType,
) -> Vec<domain::MerchantConnectorAccount> {
merchant_connector_accounts
.into_iter()
- .filter(|mca| {
- profile_id.map_or(true, |id| &mca.profile_id == id)
- && mca.connector_type == connector_type
- })
+ .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type)
.collect()
}
@@ -4269,18 +4272,12 @@ pub async fn get_apple_pay_retryable_connectors<F>(
key_store: &domain::MerchantKeyStore,
pre_routing_connector_data_list: &[api::ConnectorData],
merchant_connector_id: Option<&String>,
+ business_profile: domain::BusinessProfile,
) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
where
F: Send + Clone,
{
- let profile_id = &payment_data
- .payment_intent
- .profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "profile_id",
- })?;
+ let profile_id = &business_profile.profile_id;
let pre_decided_connector_data_first = pre_routing_connector_data_list
.first()
@@ -4318,7 +4315,7 @@ where
let profile_specific_merchant_connector_account_list =
filter_mca_based_on_profile_and_connector_type(
merchant_connector_account_list,
- Some(profile_id),
+ profile_id,
ConnectorType::PaymentProcessor,
);
@@ -4349,7 +4346,10 @@ where
}
}
}
-
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config(
&*state.clone().store,
profile_id,
@@ -4359,6 +4359,16 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let fallback_connetors_list = core_admin::BusinessProfileWrapper::new(business_profile)
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get merchant default fallback connectors config")?;
+
let mut routing_connector_data_list = Vec::new();
pre_routing_connector_data_list.iter().for_each(|pre_val| {
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 371b028154e..af5f234e2ce 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -378,7 +378,7 @@ where
let filtered_connector_accounts = helpers::filter_mca_based_on_profile_and_connector_type(
all_connector_accounts,
- Some(&profile_id),
+ &profile_id,
common_enums::ConnectorType::PaymentProcessor,
);
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index c029e2d289c..30c1edb6e04 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -34,12 +34,18 @@ use rand::{
use rustc_hash::FxHashMap;
use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+use crate::core::admin;
#[cfg(feature = "payouts")]
use crate::core::payouts;
use crate::{
core::{
errors, errors as oss_errors, payments as payments_oss,
- routing::{self, helpers as routing_helpers},
+ routing::{self},
},
logger,
types::{
@@ -75,7 +81,7 @@ pub struct SessionRoutingPmTypeInput<'a> {
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
- profile_id: Option<String>,
+ profile_id: String,
}
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
@@ -273,28 +279,31 @@ pub async fn perform_static_routing_v1<F: Clone>(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: Option<String>,
+ business_profile: &domain::BusinessProfile,
transaction_data: &routing::TransactionData<'_, F>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
- let profile_id = match transaction_data {
- routing::TransactionData::Payment(payment_data) => payment_data
- .payment_intent
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
- #[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => &payout_data.payout_attempt.profile_id,
- };
let algorithm_id = if let Some(id) = algorithm_id {
id
} else {
- let fallback_config = routing_helpers::get_merchant_default_config(
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
+ let fallback_config = routing::helpers::get_merchant_default_config(
&*state.clone().store,
- profile_id,
+ &business_profile.profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let fallback_config = admin::BusinessProfileWrapper::new(business_profile.clone())
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
return Ok(fallback_config);
};
@@ -302,7 +311,7 @@ pub async fn perform_static_routing_v1<F: Clone>(
state,
merchant_id,
&algorithm_id,
- Some(profile_id).cloned(),
+ business_profile.profile_id.clone(),
&api_enums::TransactionType::from(transaction_data),
)
.await?;
@@ -333,15 +342,10 @@ async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?;
-
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
@@ -421,15 +425,12 @@ pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
algorithm_id: &str,
- profile_id: Option<String>,
+ profile_id: String,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let algorithm = {
let algorithm = state
.store
- .find_routing_algorithm_by_profile_id_algorithm_id(
- &profile_id.unwrap_or_default(),
- algorithm_id,
- )
+ .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, algorithm_id)
.await
.change_context(errors::RoutingError::DslMissingInDb)?;
let algorithm: routing_types::RoutingAlgorithm = algorithm
@@ -506,16 +507,12 @@ pub fn perform_volume_split(
pub async fn get_merchant_cgraph<'a>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let merchant_id = &key_store.merchant_id;
let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?;
match transaction_type {
api_enums::TransactionType::Payment => {
format!("cgraph_{}_{}", merchant_id.get_string_repr(), profile_id)
@@ -549,7 +546,7 @@ pub async fn refresh_cgraph_cache<'a>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
@@ -588,7 +585,7 @@ pub async fn refresh_cgraph_cache<'a>(
let merchant_connector_accounts =
payments_oss::helpers::filter_mca_based_on_profile_and_connector_type(
merchant_connector_accounts,
- profile_id.as_ref(),
+ &profile_id,
connector_type,
);
@@ -648,7 +645,7 @@ async fn perform_cgraph_filtering(
chosen: Vec<routing_types::RoutableConnectorChoice>,
backend_input: dsl_inputs::BackendInput,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ profile_id: String,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let context = euclid_graph::AnalysisContext::from_dir_values(
@@ -692,7 +689,7 @@ pub async fn perform_eligibility_analysis<F: Clone>(
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_, F>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ profile_id: String,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
@@ -717,9 +714,13 @@ pub async fn perform_fallback_routing<F: Clone>(
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_, F>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ business_profile: &domain::BusinessProfile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
- let fallback_config = routing_helpers::get_merchant_default_config(
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+ ))]
+ let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
@@ -735,7 +736,14 @@ pub async fn perform_fallback_routing<F: Clone>(
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
-
+ #[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+ ))]
+ let fallback_config = admin::BusinessProfileWrapper::new(business_profile.clone())
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
@@ -748,7 +756,7 @@ pub async fn perform_fallback_routing<F: Clone>(
fallback_config,
backend_input,
eligible_connectors,
- profile_id,
+ business_profile.profile_id.clone(),
&api_enums::TransactionType::from(transaction_data),
)
.await
@@ -760,7 +768,7 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_, F>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
- profile_id: Option<String>,
+ business_profile: &domain::BusinessProfile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let mut final_selection = perform_eligibility_analysis(
state,
@@ -768,7 +776,7 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
chosen,
transaction_data,
eligible_connectors.as_ref(),
- profile_id.clone(),
+ business_profile.profile_id.clone(),
)
.await?;
@@ -777,7 +785,7 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
key_store,
transaction_data,
eligible_connectors.as_ref(),
- profile_id,
+ business_profile,
)
.await;
@@ -831,7 +839,7 @@ pub async fn perform_session_flow_routing(
feature = "business_profile_v2"
))]
let routing_algorithm =
- MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id);
+ MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone());
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -929,11 +937,14 @@ pub async fn perform_session_flow_routing(
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
-
- profile_id: session_input.payment_intent.profile_id.clone(),
+ profile_id: profile_id.clone(),
};
- let routable_connector_choice_option =
- perform_session_routing_for_pm_type(&session_pm_input, transaction_type).await?;
+ let routable_connector_choice_option = perform_session_routing_for_pm_type(
+ &session_pm_input,
+ transaction_type,
+ &business_profile,
+ )
+ .await?;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
@@ -964,26 +975,20 @@ pub async fn perform_session_flow_routing(
Ok(result)
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(any(feature = "routing_v2", feature = "business_profile_v2"))
+))]
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
+ _business_profile: &domain::BusinessProfile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
- #[cfg(all(
- any(feature = "v1", feature = "v2"),
- not(any(feature = "routing_v2", feature = "business_profile_v2"))
- ))]
+
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
- #[cfg(all(
- feature = "v2",
- feature = "routing_v2",
- feature = "business_profile_v2"
- ))]
- let algorithm_id = match session_pm_input.routing_algorithm {
- MerchantAccountRoutingAlgorithm::V1(algorithm_id) => algorithm_id,
- };
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
@@ -1008,13 +1013,9 @@ async fn perform_session_routing_for_pm_type(
)?,
}
} else {
- routing_helpers::get_merchant_default_config(
+ routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
- session_pm_input
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
+ &session_pm_input.profile_id,
transaction_type,
)
.await
@@ -1033,13 +1034,9 @@ async fn perform_session_routing_for_pm_type(
.await?;
if final_selection.is_empty() {
- let fallback = routing_helpers::get_merchant_default_config(
+ let fallback = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
- session_pm_input
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?,
+ &session_pm_input.profile_id,
transaction_type,
)
.await
@@ -1064,6 +1061,83 @@ async fn perform_session_routing_for_pm_type(
}
}
+#[cfg(all(
+ feature = "v2",
+ feature = "routing_v2",
+ feature = "business_profile_v2"
+))]
+async fn perform_session_routing_for_pm_type(
+ session_pm_input: &SessionRoutingPmTypeInput<'_>,
+ transaction_type: &api_enums::TransactionType,
+ business_profile: &domain::BusinessProfile,
+) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
+ let merchant_id = &session_pm_input.key_store.merchant_id;
+
+ let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
+
+ let profile_wrapper = admin::BusinessProfileWrapper::new(business_profile.clone());
+ let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
+ let cached_algorithm = ensure_algorithm_cached_v1(
+ &session_pm_input.state.clone(),
+ merchant_id,
+ algorithm_id,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+
+ match cached_algorithm.as_ref() {
+ CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
+ CachedAlgorithm::Priority(plist) => plist.clone(),
+ CachedAlgorithm::VolumeSplit(splits) => {
+ perform_volume_split(splits.to_vec(), Some(session_pm_input.attempt_id))
+ .change_context(errors::RoutingError::ConnectorSelectionFailed)?
+ }
+ CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
+ session_pm_input.backend_input.clone(),
+ interpreter,
+ )?,
+ }
+ } else {
+ profile_wrapper
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?
+ };
+
+ let mut final_selection = perform_cgraph_filtering(
+ &session_pm_input.state.clone(),
+ session_pm_input.key_store,
+ chosen_connectors,
+ session_pm_input.backend_input.clone(),
+ None,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+
+ if final_selection.is_empty() {
+ let fallback = profile_wrapper
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
+
+ final_selection = perform_cgraph_filtering(
+ &session_pm_input.state.clone(),
+ session_pm_input.key_store,
+ fallback,
+ session_pm_input.backend_input.clone(),
+ None,
+ session_pm_input.profile_id.clone(),
+ transaction_type,
+ )
+ .await?;
+ }
+
+ if final_selection.is_empty() {
+ Ok(None)
+ } else {
+ Ok(Some(final_selection))
+ }
+}
pub fn make_dsl_input_for_surcharge(
payment_attempt: &oss_storage::PaymentAttempt,
payment_intent: &oss_storage::PaymentIntent,
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index 0e480605112..d18afe02056 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -300,7 +300,7 @@ pub async fn filter_payout_methods(
// Filter MCAs based on profile_id and connector_type
let filtered_mcas = helpers::filter_mca_based_on_profile_and_connector_type(
all_mcas,
- Some(&payout.profile_id),
+ &payout.profile_id,
common_enums::ConnectorType::PayoutProcessor,
);
let address = payout
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 67e35e7dff6..4f9e3f9529e 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -33,6 +33,7 @@ use crate::{
route_connector_v1, routing, CustomerDetails,
},
routing::TransactionData,
+ utils as core_utils,
},
db::StorageInterface,
routes::{metrics, SessionState},
@@ -745,6 +746,17 @@ pub async fn decide_payout_connector(
return Ok(api::ConnectorCallType::PreDetermined(connector_data));
}
+ // Validate and get the business_profile from payout_attempt
+ let business_profile = core_utils::validate_and_get_business_profile(
+ state.store.as_ref(),
+ &(state).into(),
+ key_store,
+ Some(&payout_attempt.profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")?;
+
// 2. Check routing algorithm passed in the request
if let Some(routing_algorithm) = request_straight_through {
let (mut connectors, check_eligibility) =
@@ -759,7 +771,7 @@ pub async fn decide_payout_connector(
connectors,
&TransactionData::<()>::Payout(payout_data),
eligible_connectors,
- Some(payout_attempt.profile_id.clone()),
+ &business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -807,7 +819,7 @@ pub async fn decide_payout_connector(
connectors,
&TransactionData::<()>::Payout(payout_data),
eligible_connectors,
- Some(payout_attempt.profile_id.clone()),
+ &business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 0c50a01e36d..2b7f2d18306 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -706,7 +706,7 @@ pub async fn update_default_fallback_routing(
},
)?;
profile_wrapper
- .update_default_routing_for_profile(
+ .update_default_fallback_routing_of_connectors_under_profile(
db,
&updated_list_of_connectors,
key_manager_state,
@@ -949,7 +949,7 @@ pub async fn retrieve_linked_routing_config(
routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
))
}
-
+// List all the default fallback algorithms under all the profile under a merchant
pub async fn retrieve_default_routing_config_for_profiles(
state: SessionState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 94405a0249b..680d535a652 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -6,17 +6,21 @@ use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::errors::ReportSwitchExt;
use common_utils::ext_traits::Encode;
#[cfg(feature = "olap")]
-use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
+use diesel::{
+ associations::HasTable, ExpressionMethods, JoinOnDsl, NullableExpressionMethods, QueryDsl,
+};
#[cfg(all(
feature = "olap",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
-use diesel::{JoinOnDsl, NullableExpressionMethods};
+use diesel_models::payout_attempt::PayoutAttempt as DieselPayoutAttempt;
#[cfg(feature = "olap")]
use diesel_models::{
- customers::Customer as DieselCustomer, enums as storage_enums, query::generics::db_metrics,
- schema::payouts::dsl as po_dsl,
+ customers::Customer as DieselCustomer,
+ enums as storage_enums,
+ query::generics::db_metrics,
+ schema::{customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl, payouts::dsl as po_dsl},
};
use diesel_models::{
enums::MerchantStorageScheme,
@@ -26,15 +30,6 @@ use diesel_models::{
PayoutsUpdate as DieselPayoutsUpdate,
},
};
-#[cfg(all(
- feature = "olap",
- any(feature = "v1", feature = "v2"),
- not(feature = "customer_v2")
-))]
-use diesel_models::{
- payout_attempt::PayoutAttempt as DieselPayoutAttempt,
- schema::{customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl},
-};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payouts::PayoutFetchConstraints;
|
refactor
|
Refactor fallback routing behaviour in payments for v2 (#5642)
|
7af4c92ef25b8e2b71a6839fcd80925c09897779
|
2023-09-21 22:36:32
|
Arjun Karthik
|
chore(CODEOWNERS): update CODEOWNERS (#2254)
| false
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 900384eb96b..9a45340c6f1 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -22,6 +22,7 @@ migrations/ @juspay/hyperswitch-framework
connector-template/ @juspay/hyperswitch-connector
crates/router/src/connector/ @juspay/hyperswitch-connector
+crates/router/tests/connectors @juspay/hyperswitch-connector
crates/router/src/compatibility/ @juspay/hyperswitch-compatibility
|
chore
|
update CODEOWNERS (#2254)
|
0be900d2388ad732a40b788223bd48aee9b3aa95
|
2023-05-31 13:17:33
|
Kartikeya Hegde
|
docs: Add changelog to 0.5.15 (#1216)
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e0f3a7fb4a..61233275af1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,61 @@
All notable changes to HyperSwitch will be documented here.
+## 0.5.15 (2023-05-19)
+
+### Features
+
+- **connector:**
+ - [Bluesnap] Add support for ApplePay ([#1178](https://github.com/juspay/hyperswitch/pull/1178)) ([`919c03e`](https://github.com/juspay/hyperswitch/commit/919c03e679c4ebbb138509da52a18bface7ba319))
+ - Add Interac as Payment Method Type ([#1205](https://github.com/juspay/hyperswitch/pull/1205)) ([`afceda5`](https://github.com/juspay/hyperswitch/commit/afceda55ad9741909e21a3c3956d78b5ba858746))
+ - [Authorizedotnet] implement Capture flow and webhooks for Authorizedotnet ([#1171](https://github.com/juspay/hyperswitch/pull/1171)) ([`2d49ce5`](https://github.com/juspay/hyperswitch/commit/2d49ce56de5ed314aa099f3ce4aa569b3e22b561))
+- **db:** Implement `AddressInterface` for `MockDb` ([#968](https://github.com/juspay/hyperswitch/pull/968)) ([`39405bb`](https://github.com/juspay/hyperswitch/commit/39405bb4788bf88d6c8c166281fffc238a589aaa))
+- **documentation:** Add polymorphic `generate_schema` macro ([#1183](https://github.com/juspay/hyperswitch/pull/1183)) ([`53aa5ac`](https://github.com/juspay/hyperswitch/commit/53aa5ac92d0692b753624a4254040f8452def1d2))
+- **email:** Integrate email service using AWS SES ([#1158](https://github.com/juspay/hyperswitch/pull/1158)) ([`07e0fcb`](https://github.com/juspay/hyperswitch/commit/07e0fcbe06107e8be532b4e9a1e1a1ef6efba68e))
+- **frm_routing_algorithm:** Added frm_routing_algorithm to merchant_account table, to be consumed for frm selection ([#1161](https://github.com/juspay/hyperswitch/pull/1161)) ([`ea98145`](https://github.com/juspay/hyperswitch/commit/ea9814531880584435c122b3e32e9883e4518fd2))
+- **payments:** Add support for manual retries in payments confirm call ([#1170](https://github.com/juspay/hyperswitch/pull/1170)) ([`1f52a66`](https://github.com/juspay/hyperswitch/commit/1f52a66452042deb0e3959e839a726f261cce880))
+- **redis_interface:** Implement `MGET` command ([#1206](https://github.com/juspay/hyperswitch/pull/1206)) ([`93dcd98`](https://github.com/juspay/hyperswitch/commit/93dcd98640a31e41f0d66d2ece2396e536adefae))
+- **router:**
+ - Implement `ApiKeyInterface` for `MockDb` ([#1101](https://github.com/juspay/hyperswitch/pull/1101)) ([`95c7ca9`](https://github.com/juspay/hyperswitch/commit/95c7ca99d1b5009f4cc8664825c5e63a165006c7))
+ - Add mandates list api ([#1143](https://github.com/juspay/hyperswitch/pull/1143)) ([`commit`](https://github.com/juspay/hyperswitch/commit/75ba3ff09f71d1dd295f9dad0060d2620d7b3764))
+- **traces:** Add support for aws xray ([#1194](https://github.com/juspay/hyperswitch/pull/1194)) ([`8947e1c`](https://github.com/juspay/hyperswitch/commit/8947e1c9dba3585c3d998110b53747cbc1007bc2))
+- ACH transfers ([#905](https://github.com/juspay/hyperswitch/pull/905)) ([`23bca66`](https://github.com/juspay/hyperswitch/commit/23bca66b810993895e4054cc4bf3fdcac6b2ed4c))
+- SEPA and BACS bank transfers through stripe ([#930](https://github.com/juspay/hyperswitch/pull/930)) ([`cf00059`](https://github.com/juspay/hyperswitch/commit/cf000599ddaca2646efce0493a013c06fcdf34b8))
+
+### Bug Fixes
+
+- **connector:** [Checkout] Fix incoming webhook event mapping ([#1197](https://github.com/juspay/hyperswitch/pull/1197)) ([`912a108`](https://github.com/juspay/hyperswitch/commit/912a1084846b6dc8e843e852a3b664a4faaf9f00))
+- **core:** Add ephemeral key to payment_create response when customer_id is mentioned ([#1133](https://github.com/juspay/hyperswitch/pull/1133)) ([`f394c4a`](https://github.com/juspay/hyperswitch/commit/f394c4abc071b314798943024ba22d653a6a056e))
+- **mandate:** Throw DuplicateMandate Error if mandate insert fails ([#1201](https://github.com/juspay/hyperswitch/pull/1201)) ([`186bd72`](https://github.com/juspay/hyperswitch/commit/186bd729d672290e0f49eac0cebb3dcb8948f992))
+- **merchant_connector_account:** Add validation for the `disabled` flag ([#1141](https://github.com/juspay/hyperswitch/pull/1141)) ([`600dc33`](https://github.com/juspay/hyperswitch/commit/600dc338673c593c3cbd3ad8dfebe17d4f5c0326))
+- **router:**
+ - Aggregate critical hotfixes for v0.5.10 ([#1162](https://github.com/juspay/hyperswitch/pull/1162)) ([`ed22b2a`](https://github.com/juspay/hyperswitch/commit/ed22b2af763425d4e71cccd8da158e5e95722fed))
+ - Outgoing webhook api call ([#1193](https://github.com/juspay/hyperswitch/pull/1193)) ([`31a52d8`](https://github.com/juspay/hyperswitch/commit/31a52d8058dbee38cd77de20b7cae7c5d6fb23bf))
+ - Add dummy connector url to proxy bypass ([#1186](https://github.com/juspay/hyperswitch/pull/1186)) ([`bc5497f`](https://github.com/juspay/hyperswitch/commit/bc5497f03ab7fde585e7c57815f55cf7b4b8d475))
+ - Aggregate hotfixes for v0.5.10 ([#1204](https://github.com/juspay/hyperswitch/pull/1204)) ([`9cc1cee`](https://github.com/juspay/hyperswitch/commit/9cc1ceec6986f5696030d95e6899730807637cd9))
+- **utils:** Fix bug in email validation ([#1180](https://github.com/juspay/hyperswitch/pull/1180)) ([`5e51b6b`](https://github.com/juspay/hyperswitch/commit/5e51b6b16db6830dd5051b43fbd7d43532d9f195))
+- Fix(connector) : Added signifyd to routableconnectors for frm ([#1182](https://github.com/juspay/hyperswitch/pull/1182)) ([`2ce5d5f`](https://github.com/juspay/hyperswitch/commit/2ce5d5ffe4e37de29749fc97b13d2faaec8fcee0))
+- Handle unique constraint violation error gracefully ([#1202](https://github.com/juspay/hyperswitch/pull/1202)) ([`b3fd174`](https://github.com/juspay/hyperswitch/commit/b3fd174d04cdd4b26328d36c4f886e6ef4df830d))
+
+### Refactors
+
+- **mandate:** Allow merchant to pass the mandate details and customer acceptance separately ([#1188](https://github.com/juspay/hyperswitch/pull/1188)) ([`6c41cdb`](https://github.com/juspay/hyperswitch/commit/6c41cdb1c942d3152c73a44b62dd9a02587f6bd8))
+- Use `strum::EnumString` implementation for connector name conversions ([#1052](https://github.com/juspay/hyperswitch/pull/1052)) ([`2809425`](https://github.com/juspay/hyperswitch/commit/28094251546b6067a44df8ae906d9cd04f85e84e))
+
+### Documentation
+
+- Add changelog for v0.5.14 ([#1177](https://github.com/juspay/hyperswitch/pull/1177)) ([`236124d`](https://github.com/juspay/hyperswitch/commit/236124d1993c2a7d52e30441761a3558ad02c973))
+
+### Miscellaneous Tasks
+
+- **CODEOWNERS:** Add hyperswitch-maintainers as default owners for all files ([#1210](https://github.com/juspay/hyperswitch/pull/1210)) ([`985670d`](https://github.com/juspay/hyperswitch/commit/985670da9c90cbc904162d7863c9c508f5cf5e19))
+- **git-cliff:** Simplify `git-cliff` config files ([#1213](https://github.com/juspay/hyperswitch/pull/1213)) ([`bd0069e`](https://github.com/juspay/hyperswitch/commit/bd0069e2a8bd3c3389c92590c688ce945cd7ebec))
+
+### Revert
+
+- **connector:** Fix stripe status to attempt status map ([#1179](https://github.com/juspay/hyperswitch/pull/1179)) ([`bd8868e`](https://github.com/juspay/hyperswitch/commit/bd8868efd00748cf64c46519c4ed7ba04ad06d5e))
+- Fix(connector): Added signifyd to routableconnectors for frm ([#1203](https://github.com/juspay/hyperswitch/pull/1203)) ([`dbc5bc5`](https://github.com/juspay/hyperswitch/commit/dbc5bc538a218ae287e96c44de0223c26c1583f0))
+
## 0.5.14 (2023-05-16)
### Features
|
docs
|
Add changelog to 0.5.15 (#1216)
|
ad4b7de628ca4e0f56a06d8b9f5e2c8c5bace67a
|
2023-09-11 17:33:47
|
Sampras Lopes
|
refactor(storage_impl): split payment attempt models to domain + diesel (#2010)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index bddc9e50dfe..092a1018cca 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1743,6 +1743,7 @@ dependencies = [
"common_enums",
"common_utils",
"error-stack",
+ "masking",
"serde",
"serde_json",
"strum 0.25.0",
@@ -4518,18 +4519,18 @@ dependencies = [
[[package]]
name = "serde"
-version = "1.0.164"
+version = "1.0.188"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d"
+checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.164"
+version = "1.0.188"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68"
+checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
dependencies = [
"proc-macro2",
"quote",
@@ -4538,11 +4539,11 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.96"
+version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1"
+checksum = "693151e1ac27563d6dbcec9dee9fbd5da8539b20fa14ad3752b2e6d363ace360"
dependencies = [
- "indexmap 1.9.3",
+ "indexmap 2.0.0",
"itoa",
"ryu",
"serde",
@@ -4842,6 +4843,7 @@ dependencies = [
"ring",
"router_env",
"serde",
+ "serde_json",
"thiserror",
"tokio",
]
diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml
index 7b930d073db..10b4fb509e8 100644
--- a/crates/common_enums/Cargo.toml
+++ b/crates/common_enums/Cargo.toml
@@ -15,7 +15,7 @@ diesel = { version = "2.1.0", features = ["postgres"] }
serde = { version = "1.0.160", features = [ "derive" ] }
serde_json = "1.0.96"
strum = { version = "0.25", features = [ "derive" ] }
-time = { version = "0.3.20", features = ["serde", "serde-well-known", "std"] }
+time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] }
utoipa = { version = "3.3.0", features = ["preserve_order"] }
# First party crates
diff --git a/crates/data_models/Cargo.toml b/crates/data_models/Cargo.toml
index e0b47bf129d..254c194182f 100644
--- a/crates/data_models/Cargo.toml
+++ b/crates/data_models/Cargo.toml
@@ -15,6 +15,7 @@ olap = []
[dependencies]
# First party deps
api_models = { version = "0.1.0", path = "../api_models" }
+masking = { version = "0.1.0", path = "../masking" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs
index 6ea40a286e9..afdcda3a40e 100644
--- a/crates/data_models/src/mandates.rs
+++ b/crates/data_models/src/mandates.rs
@@ -1,5 +1,12 @@
+use api_models::payments::{
+ AcceptanceType as ApiAcceptanceType, CustomerAcceptance as ApiCustomerAcceptance,
+ MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType,
+ OnlineMandate as ApiOnlineMandate,
+};
use common_enums::Currency;
-use common_utils::pii;
+use common_utils::{date_time, errors::ParsingError, pii};
+use error_stack::{IntoReport, ResultExt};
+use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
@@ -17,3 +24,135 @@ pub struct MandateAmountData {
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
}
+
+// The fields on this struct are optional, as we want to allow the merchant to provide partial
+// information about creating mandates
+#[derive(Default, Eq, PartialEq, Debug, Clone)]
+pub struct MandateData {
+ /// A concent from the customer to store the payment method
+ pub customer_acceptance: Option<CustomerAcceptance>,
+ /// A way to select the type of mandate used
+ pub mandate_type: Option<MandateDataType>,
+}
+
+#[derive(Default, Eq, PartialEq, Debug, Clone)]
+pub struct CustomerAcceptance {
+ /// Type of acceptance provided by the
+ pub acceptance_type: AcceptanceType,
+ /// Specifying when the customer acceptance was provided
+ pub accepted_at: Option<PrimitiveDateTime>,
+ /// Information required for online mandate generation
+ pub online: Option<OnlineMandate>,
+}
+
+#[derive(Default, Debug, PartialEq, Eq, Clone)]
+pub enum AcceptanceType {
+ Online,
+ #[default]
+ Offline,
+}
+
+#[derive(Default, Eq, PartialEq, Debug, Clone)]
+pub struct OnlineMandate {
+ /// Ip address of the customer machine from which the mandate was created
+ pub ip_address: Option<Secret<String, pii::IpAddress>>,
+ /// The user-agent of the customer's browser
+ pub user_agent: String,
+}
+
+impl From<MandateType> for MandateDataType {
+ fn from(mandate_type: MandateType) -> Self {
+ match mandate_type {
+ MandateType::SingleUse(mandate_amount_data) => {
+ Self::SingleUse(mandate_amount_data.into())
+ }
+ MandateType::MultiUse(mandate_amount_data) => {
+ Self::MultiUse(mandate_amount_data.map(|d| d.into()))
+ }
+ }
+ }
+}
+
+impl From<ApiMandateAmountData> for MandateAmountData {
+ fn from(value: ApiMandateAmountData) -> Self {
+ Self {
+ amount: value.amount,
+ currency: value.currency,
+ start_date: value.start_date,
+ end_date: value.end_date,
+ metadata: value.metadata,
+ }
+ }
+}
+
+impl From<ApiMandateData> for MandateData {
+ fn from(value: ApiMandateData) -> Self {
+ Self {
+ customer_acceptance: value.customer_acceptance.map(|d| d.into()),
+ mandate_type: value.mandate_type.map(|d| d.into()),
+ }
+ }
+}
+
+impl From<ApiCustomerAcceptance> for CustomerAcceptance {
+ fn from(value: ApiCustomerAcceptance) -> Self {
+ Self {
+ acceptance_type: value.acceptance_type.into(),
+ accepted_at: value.accepted_at,
+ online: value.online.map(|d| d.into()),
+ }
+ }
+}
+
+impl From<ApiAcceptanceType> for AcceptanceType {
+ fn from(value: ApiAcceptanceType) -> Self {
+ match value {
+ ApiAcceptanceType::Online => Self::Online,
+ ApiAcceptanceType::Offline => Self::Offline,
+ }
+ }
+}
+
+impl From<ApiOnlineMandate> for OnlineMandate {
+ fn from(value: ApiOnlineMandate) -> Self {
+ Self {
+ ip_address: value.ip_address,
+ user_agent: value.user_agent,
+ }
+ }
+}
+
+impl CustomerAcceptance {
+ pub fn get_ip_address(&self) -> Option<String> {
+ self.online
+ .as_ref()
+ .and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned()))
+ }
+
+ pub fn get_user_agent(&self) -> Option<String> {
+ self.online.as_ref().map(|data| data.user_agent.clone())
+ }
+
+ pub fn get_accepted_at(&self) -> PrimitiveDateTime {
+ self.accepted_at
+ .unwrap_or_else(common_utils::date_time::now)
+ }
+}
+
+impl MandateAmountData {
+ pub fn get_end_date(
+ &self,
+ format: date_time::DateFormat,
+ ) -> error_stack::Result<Option<String>, ParsingError> {
+ self.end_date
+ .map(|date| {
+ date_time::format_date(date, format)
+ .into_report()
+ .change_context(ParsingError::DateTimeParsingError)
+ })
+ .transpose()
+ }
+ pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
+ self.metadata.clone()
+ }
+}
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index d6b9d48f03e..68e083abd1a 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -1,3 +1,4 @@
+use api_models::enums::Connector;
use common_enums as storage_enums;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -77,6 +78,15 @@ pub trait PaymentAttemptInterface {
merchant_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentListFilters, errors::StorageError>;
+
+ async fn get_total_count_of_filtered_payment_attempts(
+ &self,
+ merchant_id: &str,
+ active_attempt_ids: &[String],
+ connector: Option<Vec<Connector>>,
+ payment_methods: Option<Vec<storage_enums::PaymentMethod>>,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<i64, errors::StorageError>;
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
@@ -129,7 +139,7 @@ pub struct PaymentAttempt {
pub connector_response_reference_id: Option<String>,
}
-#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PaymentListFilters {
pub connector: Vec<String>,
pub currency: Vec<storage_enums::Currency>,
@@ -222,6 +232,13 @@ pub enum PaymentAttemptUpdate {
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
straight_through_algorithm: Option<serde_json::Value>,
+ error_code: Option<Option<String>>,
+ error_message: Option<Option<String>>,
+ },
+ RejectUpdate {
+ status: storage_enums::AttemptStatus,
+ error_code: Option<Option<String>>,
+ error_message: Option<Option<String>>,
},
VoidUpdate {
status: storage_enums::AttemptStatus,
@@ -261,9 +278,8 @@ pub enum PaymentAttemptUpdate {
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
},
- MultipleCaptureUpdate {
- status: Option<storage_enums::AttemptStatus>,
- multiple_capture_count: Option<i16>,
+ MultipleCaptureCountUpdate {
+ multiple_capture_count: i16,
},
PreprocessingUpdate {
status: storage_enums::AttemptStatus,
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index d87b8715f76..c22151d3803 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -14,7 +14,6 @@ use crate::{
errors::{self, DatabaseError},
payment_attempt::{
PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal,
- PaymentListFilters,
},
payment_intent::PaymentIntent,
query::generics::db_metrics,
@@ -212,15 +211,20 @@ impl PaymentAttempt {
conn: &PgPooledConn,
pi: &[PaymentIntent],
merchant_id: &str,
- ) -> StorageResult<PaymentListFilters> {
- let active_attempt_ids: Vec<String> = pi
+ ) -> StorageResult<(
+ Vec<String>,
+ Vec<enums::Currency>,
+ Vec<IntentStatus>,
+ Vec<enums::PaymentMethod>,
+ )> {
+ let active_attempts: Vec<String> = pi
.iter()
.map(|payment_intent| payment_intent.clone().active_attempt_id)
.collect();
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .filter(dsl::attempt_id.eq_any(active_attempt_ids));
+ .filter(dsl::attempt_id.eq_any(active_attempts));
let intent_status: Vec<IntentStatus> = pi
.iter()
@@ -268,14 +272,12 @@ impl PaymentAttempt {
.flatten()
.collect::<Vec<enums::PaymentMethod>>();
- let filters = PaymentListFilters {
- connector: filter_connector,
- currency: filter_currency,
- status: intent_status,
- payment_method: filter_payment_method,
- };
-
- Ok(filters)
+ Ok((
+ filter_connector,
+ filter_currency,
+ intent_status,
+ filter_payment_method,
+ ))
}
pub async fn get_total_count_of_attempts(
conn: &PgPooledConn,
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index b8c5caf1782..21b72955414 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -4,6 +4,7 @@ use common_utils::{
date_time, fp_utils, pii,
pii::Email,
};
+use data_models::mandates::MandateDataType;
use error_stack::{IntoReport, ResultExt};
use masking::{PeekInterface, Secret};
use reqwest::Url;
@@ -11,8 +12,8 @@ use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{
- self, AddressDetailsData, BrowserInformationData, MandateData,
- PaymentsAuthorizeRequestData, PaymentsCancelRequestData, RouterData,
+ self, AddressDetailsData, BrowserInformationData, PaymentsAuthorizeRequestData,
+ PaymentsCancelRequestData, RouterData,
},
consts,
core::errors,
@@ -790,20 +791,28 @@ fn get_card_info<F>(
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "mandate_type",
})? {
- payments::MandateType::SingleUse(details) => details,
- payments::MandateType::MultiUse(details) => {
+ MandateDataType::SingleUse(details) => details,
+ MandateDataType::MultiUse(details) => {
details.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "mandate_data.mandate_type.multi_use",
})?
}
};
- let mandate_meta: NuveiMandateMeta =
- utils::to_connector_meta_from_secret(Some(details.get_metadata()?))?;
+ let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(
+ Some(details.get_metadata().ok_or_else(utils::missing_field_err(
+ "mandate_data.mandate_type.{multi_use|single_use}.metadata",
+ ))?),
+ )?;
(
Some("0".to_string()), // In case of first installment, rebilling should be 0
Some(V2AdditionalParams {
rebill_expiry: Some(
- details.get_end_date(date_time::DateFormat::YYYYMMDD)?,
+ details
+ .get_end_date(date_time::DateFormat::YYYYMMDD)
+ .change_context(errors::ConnectorError::DateFormattingFailed)?
+ .ok_or_else(utils::missing_field_err(
+ "mandate_data.mandate_type.{multi_use|single_use}.end_date",
+ ))?,
),
rebill_frequency: Some(mandate_meta.frequency),
challenge_window_size: None,
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 3865e198583..fd49046bf36 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -6,6 +6,7 @@ use common_utils::{
ext_traits::{ByteSliceExt, BytesExt},
pii::{self, Email},
};
+use data_models::mandates::AcceptanceType;
use error_stack::{IntoReport, ResultExt};
use masking::{ExposeInterface, ExposeOptionInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -1672,7 +1673,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
.map(|customer_acceptance| {
Ok::<_, error_stack::Report<errors::ConnectorError>>(
match customer_acceptance.acceptance_type {
- payments::AcceptanceType::Online => {
+ AcceptanceType::Online => {
let online_mandate = customer_acceptance
.online
.clone()
@@ -1696,7 +1697,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
},
}
}
- payments::AcceptanceType::Offline => StripeMandateRequest {
+ AcceptanceType::Offline => StripeMandateRequest {
mandate_type: StripeMandateType::Offline,
},
},
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index f5b004046f9..34268870fb3 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -322,5 +322,5 @@ 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) -> api_models::payments::PaymentMethodData;
- fn get_setup_mandate_details(&self) -> Option<&api_models::payments::MandateData>;
+ fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData>;
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fffd127937f..6a8f804759c 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -48,7 +48,7 @@ use crate::{
types::{decrypt, encrypt_optional, AsyncLift},
},
storage::{self, enums},
- transformers::{ForeignFrom, ForeignInto},
+ transformers::ForeignFrom,
},
utils::{self, ConnectorResponseExt, OptionExt},
};
@@ -1249,9 +1249,31 @@ pub async fn list_payment_methods(
redirect_url: merchant_account.return_url,
merchant_name: merchant_account.merchant_name,
payment_methods: payment_method_responses,
- mandate_payment: payment_attempt
- .and_then(|inner| inner.mandate_details)
- .map(ForeignInto::foreign_into),
+ mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map(
+ |d| match d {
+ data_models::mandates::MandateDataType::SingleUse(i) => {
+ api::MandateType::SingleUse(api::MandateAmountData {
+ amount: i.amount,
+ currency: i.currency,
+ start_date: i.start_date,
+ end_date: i.end_date,
+ metadata: i.metadata,
+ })
+ }
+ data_models::mandates::MandateDataType::MultiUse(Some(i)) => {
+ api::MandateType::MultiUse(Some(api::MandateAmountData {
+ amount: i.amount,
+ currency: i.currency,
+ start_date: i.start_date,
+ end_date: i.end_date,
+ metadata: i.metadata,
+ }))
+ }
+ data_models::mandates::MandateDataType::MultiUse(None) => {
+ api::MandateType::MultiUse(None)
+ }
+ },
+ ),
},
))
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index b5f8f22363a..a47f52c65a0 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -11,6 +11,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant};
use api_models::payments::HeaderPayload;
use common_utils::{ext_traits::AsyncExt, pii};
+use data_models::mandates::MandateData;
use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
use error_stack::{IntoReport, ResultExt};
use futures::future::join_all;
@@ -31,6 +32,8 @@ use self::{
operations::{payment_complete_authorize, BoxedOperation, Operation},
};
use super::errors::StorageErrorExt;
+#[cfg(feature = "olap")]
+use crate::types::transformers::ForeignFrom;
use crate::{
configs::settings::PaymentMethodTypeTokenFilter,
core::{
@@ -1378,7 +1381,7 @@ where
pub mandate_id: Option<api_models::payments::MandateIds>,
pub mandate_connector: Option<String>,
pub currency: storage_enums::Currency,
- pub setup_mandate: Option<api::MandateData>,
+ pub setup_mandate: Option<MandateData>,
pub address: PaymentAddress,
pub token: Option<String>,
pub confirm: Option<bool>,
@@ -1505,7 +1508,7 @@ pub async fn list_payments(
merchant: domain::MerchantAccount,
constraints: api::PaymentListConstraints,
) -> RouterResponse<api::PaymentListResponse> {
- use crate::types::transformers::ForeignFrom;
+ use data_models::errors::StorageError;
helpers::validate_payment_list_request(&constraints)?;
let merchant_id = &merchant.merchant_id;
@@ -1527,16 +1530,16 @@ pub async fn list_payments(
.await
{
Ok(pa) => Some(Ok((pi, pa))),
- Err(e) => {
- if e.current_context().is_db_not_found() {
+ Err(error) => {
+ if matches!(error.current_context(), StorageError::ValueNotFound(_)) {
logger::warn!(
- "payment_attempts missing for payment_id : {} | error : {}",
+ ?error,
+ "payment_attempts missing for payment_id : {}",
pi.payment_id,
- e
);
return None;
}
- Some(Err(e))
+ Some(Err(error))
}
}
}
@@ -1571,10 +1574,6 @@ pub async fn apply_filters_on_payments(
merchant: domain::MerchantAccount,
constraints: api::PaymentListFilterConstraints,
) -> RouterResponse<api::PaymentListResponseV2> {
- use storage_impl::DataModelExt;
-
- use crate::types::transformers::ForeignFrom;
-
let limit = &constraints.limit;
helpers::validate_payment_list_request_for_joins(*limit)?;
@@ -1587,7 +1586,7 @@ pub async fn apply_filters_on_payments(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?
.into_iter()
- .map(|(pi, pa)| (pi, pa.to_storage_model()))
+ .map(|(pi, pa)| (pi, pa))
.collect();
let data: Vec<api::PaymentsResponse> =
@@ -1628,8 +1627,6 @@ pub async fn get_filters_for_payments(
merchant: domain::MerchantAccount,
time_range: api::TimeRange,
) -> RouterResponse<api::PaymentListFilters> {
- use crate::types::transformers::ForeignFrom;
-
let pi = db
.filter_payment_intents_by_time_range_constraints(
&merchant.merchant_id,
@@ -1649,9 +1646,14 @@ pub async fn get_filters_for_payments(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- let filters: api::PaymentListFilters = ForeignFrom::foreign_from(filters);
-
- Ok(services::ApplicationResponse::Json(filters))
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListFilters {
+ connector: filters.connector,
+ currency: filters.currency,
+ status: filters.status,
+ payment_method: filters.payment_method,
+ },
+ ))
}
pub async fn add_process_sync_task(
@@ -1844,7 +1846,7 @@ pub fn decide_connector(
if let Some(ref connector_name) = routing_data.routed_through {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
- connector_name,
+ connector_name.as_str(),
api::GetToken::Connector,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 7793a7eb0da..272ccfced60 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -248,7 +248,7 @@ 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<&api_models::payments::MandateData> {
+ fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs
index c18e25d467e..1ecf2199b80 100644
--- a/crates/router/src/core/payments/flows/verify_flow.rs
+++ b/crates/router/src/core/payments/flows/verify_flow.rs
@@ -232,7 +232,7 @@ impl mandate::MandateBehaviour for types::VerifyRequestData {
self.payment_method_data.clone()
}
- fn get_setup_mandate_details(&self) -> Option<&api_models::payments::MandateData> {
+ fn get_setup_mandate_details(&self) -> Option<&data_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index ed94e2a3d64..549f0d548ca 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -5,8 +5,11 @@ use common_utils::{
ext_traits::{AsyncExt, ByteSliceExt, ValueExt},
fp_utils, generate_id, pii,
};
-use data_models::payments::payment_intent::PaymentIntent;
-use diesel_models::{enums, payment_attempt::PaymentAttempt};
+use data_models::{
+ mandates::MandateData,
+ payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent},
+};
+use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
use error_stack::{report, IntoReport, ResultExt};
#[cfg(feature = "kms")]
@@ -43,13 +46,13 @@ use crate::{
routes::{metrics, payment_methods, AppState},
services,
types::{
- api::{self, admin, enums as api_enums, CustomerAcceptanceExt, MandateValidationFieldsExt},
+ api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{
self,
types::{self, AsyncLift},
},
storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update},
- transformers::ForeignTryFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
ErrorResponse, RouterData,
},
utils::{
@@ -282,16 +285,14 @@ pub async fn get_token_pm_type_mandate_details(
Option<String>,
Option<storage_enums::PaymentMethod>,
Option<storage_enums::PaymentMethodType>,
- Option<api::MandateData>,
+ Option<MandateData>,
Option<payments::RecurringMandatePaymentData>,
Option<String>,
)> {
+ let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from);
match mandate_type {
Some(api::MandateTransactionType::NewMandateTransaction) => {
- let setup_mandate = request
- .mandate_data
- .clone()
- .get_required_value("mandate_data")?;
+ let setup_mandate = mandate_data.clone().get_required_value("mandate_data")?;
Ok((
request.payment_token.to_owned(),
request.payment_method,
@@ -322,7 +323,7 @@ pub async fn get_token_pm_type_mandate_details(
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
- request.mandate_data.clone(),
+ mandate_data,
None,
None,
)),
@@ -662,7 +663,7 @@ pub fn create_redirect_url(
format!(
"{}/payments/{}/{}/redirect/response/{}",
router_base_url, payment_attempt.payment_id, payment_attempt.merchant_id, connector_name,
- ) + &creds_identifier_path
+ ) + creds_identifier_path.as_ref()
}
pub fn create_webhook_url(
@@ -1935,7 +1936,7 @@ pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool {
pub fn generate_mandate(
merchant_id: String,
connector: String,
- setup_mandate_details: Option<api::MandateData>,
+ setup_mandate_details: Option<MandateData>,
customer: &Option<domain::Customer>,
payment_method_id: String,
connector_mandate_id: Option<pii::SecretSerdeValue>,
@@ -1976,13 +1977,13 @@ pub fn generate_mandate(
Ok(Some(
match data.mandate_type.get_required_value("mandate_type")? {
- api::MandateType::SingleUse(data) => new_mandate
+ 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(),
- api::MandateType::MultiUse(op_data) => match op_data {
+ data_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))
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 804ef0f6346..3c58864568b 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -2,6 +2,7 @@ use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
+use data_models::mandates::MandateData;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
@@ -21,7 +22,6 @@ use crate::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
- transformers::ForeignInto,
},
utils::{self, OptionExt},
};
@@ -195,12 +195,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData {
+ let setup_mandate = setup_mandate.map(|mandate_data| MandateData {
customer_acceptance: mandate_data.customer_acceptance,
mandate_type: payment_attempt
.mandate_details
.clone()
- .map(ForeignInto::foreign_into)
.or(mandate_data.mandate_type),
});
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 3848199fba6..b2f1c5bd254 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -19,7 +19,7 @@ use crate::{
types::{
api::{self, PaymentIdTypeExt},
domain,
- storage::{self, enums, ConnectorResponseExt, PaymentAttemptExt},
+ storage::{self, enums, payment_attempt::PaymentAttemptExt, ConnectorResponseExt},
},
utils::OptionExt,
};
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 5ad04c5df35..c06c8e4e776 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -21,7 +21,6 @@ use crate::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
- transformers::ForeignInto,
},
utils::{self, OptionExt},
};
@@ -194,14 +193,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData {
- customer_acceptance: mandate_data.customer_acceptance,
- mandate_type: payment_attempt
- .mandate_details
- .clone()
- .map(ForeignInto::foreign_into)
- .or(mandate_data.mandate_type),
- });
+ let setup_mandate = setup_mandate.map(Into::into);
Ok((
Box::new(self),
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index bccfbd81c3b..f8150283cbe 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -13,7 +13,6 @@ use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
- utils as core_utils,
},
db::StorageInterface,
routes::AppState,
@@ -23,7 +22,6 @@ use crate::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
- transformers::ForeignInto,
},
utils::{self, OptionExt},
};
@@ -315,14 +313,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.or(payment_attempt.business_sub_label);
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData {
- customer_acceptance: mandate_data.customer_acceptance,
- mandate_type: payment_attempt
- .mandate_details
- .clone()
- .map(ForeignInto::foreign_into)
- .or(mandate_data.mandate_type),
- });
+ let setup_mandate = setup_mandate.map(Into::into);
Ok((
Box::new(self),
@@ -627,7 +618,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
- let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?;
+ let payment_id =
+ crate::core::utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?;
Ok((
Box::new(self),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 68f37eaa574..6a3e4cb74e8 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -3,6 +3,7 @@ use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
+use data_models::mandates::MandateData;
use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
use router_derive::PaymentOperation;
@@ -27,7 +28,6 @@ use crate::{
self,
enums::{self, IntentStatus},
},
- transformers::ForeignInto,
},
utils::{self, OptionExt},
};
@@ -242,13 +242,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData {
- customer_acceptance: mandate_data.customer_acceptance,
- mandate_type: mandate_data.mandate_type.or(payment_attempt
- .mandate_details
- .clone()
- .map(ForeignInto::foreign_into)),
- });
+ let setup_mandate: Option<MandateData> = setup_mandate.map(Into::into);
Ok((
operation,
@@ -576,7 +570,7 @@ impl PaymentCreate {
mandate_details: request
.mandate_data
.as_ref()
- .and_then(|inner| inner.mandate_type.clone().map(ForeignInto::foreign_into)),
+ .and_then(|inner| inner.mandate_type.clone().map(Into::into)),
..storage::PaymentAttemptNew::default()
})
}
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index 8641d3b1f8d..2f260ee3e0a 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -171,7 +171,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
email: None,
mandate_id: None,
mandate_connector: None,
- setup_mandate: request.mandate_data.clone(),
+ setup_mandate: request.mandate_data.clone().map(Into::into),
token: request.payment_token.clone(),
connector_response,
payment_method_data: request.payment_method_data.clone(),
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 0f34839962d..6d3c4d776ac 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -2,7 +2,7 @@ use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
-use common_utils::{errors::ReportSwitchExt, ext_traits::AsyncExt};
+use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
@@ -432,8 +432,7 @@ pub async fn get_payment_intent_payment_attempt(
pi.active_attempt_id.as_str(),
storage_scheme,
)
- .await
- .switch()?;
+ .await?;
}
api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => {
pa = db
@@ -442,8 +441,7 @@ pub async fn get_payment_intent_payment_attempt(
id,
storage_scheme,
)
- .await
- .switch()?;
+ .await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
pa.payment_id.as_str(),
@@ -455,8 +453,7 @@ pub async fn get_payment_intent_payment_attempt(
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {
pa = db
.find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)
- .await
- .switch()?;
+ .await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
pa.payment_id.as_str(),
@@ -472,8 +469,7 @@ pub async fn get_payment_intent_payment_attempt(
merchant_id,
storage_scheme,
)
- .await
- .switch()?;
+ .await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index dbd61d274d5..647979a118e 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -21,7 +21,6 @@ use crate::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
- transformers::ForeignInto,
},
utils::OptionExt,
};
@@ -304,13 +303,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(|mandate_data| api_models::payments::MandateData {
- customer_acceptance: mandate_data.customer_acceptance,
- mandate_type: mandate_data.mandate_type.or(payment_attempt
- .mandate_details
- .clone()
- .map(ForeignInto::foreign_into)),
- });
+ let setup_mandate = setup_mandate.map(Into::into);
Ok((
next_operation,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 680698e9bd8..25c9fb2c847 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -2,7 +2,8 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr};
use api_models::payments::FrmMessage;
use common_utils::fp_utils;
-use diesel_models::{ephemeral_key, payment_attempt::PaymentListFilters};
+use data_models::mandates::MandateData;
+use diesel_models::ephemeral_key;
use error_stack::{IntoReport, ResultExt};
use router_env::{instrument, tracing};
@@ -344,7 +345,7 @@ pub fn payments_to_payments_response<R, Op>(
ephemeral_key_option: Option<ephemeral_key::EphemeralKey>,
session_tokens: Vec<api::SessionToken>,
fraud_check: Option<payments::FraudCheck>,
- mandate_data: Option<api_models::payments::MandateData>,
+ mandate_data: Option<MandateData>,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
) -> RouterResponse<api::PaymentsResponse>
@@ -551,7 +552,50 @@ where
)
.set_mandate_id(mandate_id)
.set_mandate_data(
- mandate_data.map(api::MandateData::from),
+ mandate_data.map(|d| api::MandateData {
+ customer_acceptance: d.customer_acceptance.map(|d| {
+ api::CustomerAcceptance {
+ acceptance_type: match d.acceptance_type {
+ data_models::mandates::AcceptanceType::Online => {
+ api::AcceptanceType::Online
+ }
+ data_models::mandates::AcceptanceType::Offline => {
+ api::AcceptanceType::Offline
+ }
+ },
+ accepted_at: d.accepted_at,
+ online: d.online.map(|d| api::OnlineMandate {
+ ip_address: d.ip_address,
+ user_agent: d.user_agent,
+ }),
+ }
+ }),
+ mandate_type: d.mandate_type.map(|d| match d {
+ data_models::mandates::MandateDataType::MultiUse(Some(i)) => {
+ api::MandateType::MultiUse(Some(api::MandateAmountData {
+ amount: i.amount,
+ currency: i.currency,
+ start_date: i.start_date,
+ end_date: i.end_date,
+ metadata: i.metadata,
+ }))
+ }
+ data_models::mandates::MandateDataType::SingleUse(i) => {
+ api::MandateType::SingleUse(
+ api::payments::MandateAmountData {
+ amount: i.amount,
+ currency: i.currency,
+ start_date: i.start_date,
+ end_date: i.end_date,
+ metadata: i.metadata,
+ },
+ )
+ }
+ data_models::mandates::MandateDataType::MultiUse(None) => {
+ api::MandateType::MultiUse(None)
+ }
+ }),
+ }),
auth_flow == services::AuthFlow::Merchant,
)
.set_description(payment_intent.description)
@@ -777,17 +821,6 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
}
}
-impl ForeignFrom<PaymentListFilters> for api_models::payments::PaymentListFilters {
- fn foreign_from(item: PaymentListFilters) -> Self {
- Self {
- connector: item.connector,
- currency: item.currency,
- status: item.status,
- payment_method: item.payment_method,
- }
- }
-}
-
impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse {
fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self {
Self {
diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs
index ec5d138639e..88e8e59ed32 100644
--- a/crates/router/src/core/refunds/validator.rs
+++ b/crates/router/src/core/refunds/validator.rs
@@ -144,7 +144,7 @@ pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::Api
}
pub fn validate_for_valid_refunds(
- payment_attempt: &diesel_models::payment_attempt::PaymentAttempt,
+ payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt,
connector: api_models::enums::Connector,
) -> RouterResult<()> {
let payment_method = payment_attempt
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 13878b47417..14a3b777149 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -903,7 +903,7 @@ pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
pub fn get_connector_request_reference_id(
conf: &settings::Settings,
merchant_id: &str,
- payment_attempt: &diesel_models::payment_attempt::PaymentAttempt,
+ payment_attempt: &data_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 bc1fa3f9149..adf1f2fef8e 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -241,7 +241,8 @@ pub async fn get_payment_attempt_from_object_reference_id(
state: &AppState,
object_reference_id: api_models::webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
-) -> CustomResult<diesel_models::payment_attempt::PaymentAttempt, errors::ApiErrorResponse> {
+) -> CustomResult<data_models::payments::payment_attempt::PaymentAttempt, errors::ApiErrorResponse>
+{
let db = &*state.store;
match object_reference_id {
api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db
@@ -279,7 +280,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: &diesel_models::payment_attempt::PaymentAttempt,
+ payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt,
event_type: api_models::webhooks::IncomingWebhookEvent,
connector_name: &str,
) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> {
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index eeeba2b756b..389229742f3 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -17,14 +17,15 @@ pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
-pub mod payment_attempt;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod refund;
pub mod reverse_lookup;
-use data_models::payments::payment_intent::PaymentIntentInterface;
+use data_models::payments::{
+ payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface,
+};
use masking::PeekInterface;
use storage_impl::{redis::kv_store::RedisConnInterface, MockDb};
@@ -58,7 +59,7 @@ pub trait StorageInterface:
+ merchant_account::MerchantAccountInterface
+ merchant_connector_account::ConnectorAccessToken
+ merchant_connector_account::MerchantConnectorAccountInterface
- + payment_attempt::PaymentAttemptInterface
+ + PaymentAttemptInterface
+ PaymentIntentInterface
+ payment_method::PaymentMethodInterface
+ scheduler::SchedulerInterface
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs
index 19d5e73d1c9..4ba9e47e9a5 100644
--- a/crates/router/src/db/api_keys.rs
+++ b/crates/router/src/db/api_keys.rs
@@ -390,7 +390,10 @@ mod tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
async fn test_mockdb_api_key_interface() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let key1 = mockdb
.insert_api_key(storage::ApiKeyNew {
@@ -473,7 +476,10 @@ mod tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
async fn test_api_keys_cache() {
- let db = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let db = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let redis_conn = db.get_redis_conn().unwrap();
redis_conn
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index b6c102693c8..71f47872c09 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -371,6 +371,7 @@ mod tests {
enums::{DisputeStage, DisputeStatus},
};
use masking::Secret;
+ use redis_interface::RedisSettings;
use serde_json::Value;
use time::macros::datetime;
@@ -409,7 +410,10 @@ mod tests {
#[tokio::test]
async fn test_insert_dispute() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&RedisSettings::default())
+ .await
+ .expect("Failed to create a mock DB");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -437,7 +441,10 @@ mod tests {
#[tokio::test]
async fn test_find_by_merchant_id_payment_id_connector_dispute_id() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -477,7 +484,10 @@ mod tests {
#[tokio::test]
async fn test_find_dispute_by_merchant_id_dispute_id() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -511,7 +521,10 @@ mod tests {
#[tokio::test]
async fn test_find_disputes_by_merchant_id() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -561,7 +574,10 @@ mod tests {
#[tokio::test]
async fn test_find_disputes_by_merchant_id_payment_id() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -614,7 +630,10 @@ mod tests {
#[tokio::test]
async fn test_update_dispute_update() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -691,7 +710,10 @@ mod tests {
#[tokio::test]
async fn test_update_dispute_update_status() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
@@ -763,7 +785,10 @@ mod tests {
#[tokio::test]
async fn test_update_dispute_update_evidence() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 0e88d531084..3d87fc70ea1 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -108,7 +108,10 @@ mod tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
async fn test_mockdb_event_interface() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let event1 = mockdb
.insert_event(storage::EventNew {
diff --git a/crates/router/src/db/locker_mock_up.rs b/crates/router/src/db/locker_mock_up.rs
index b47484c6101..ca3028486bb 100644
--- a/crates/router/src/db/locker_mock_up.rs
+++ b/crates/router/src/db/locker_mock_up.rs
@@ -163,7 +163,10 @@ mod tests {
#[tokio::test]
async fn find_locker_by_card_id() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_locker = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
@@ -191,7 +194,10 @@ mod tests {
#[tokio::test]
async fn insert_locker_mock_up() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_locker = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
@@ -218,7 +224,10 @@ mod tests {
#[tokio::test]
async fn delete_locker_mock_up() {
- let mockdb = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let created_locker = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 501a71bb9fe..954dead0269 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -772,7 +772,7 @@ mod merchant_connector_account_cache_tests {
},
services,
types::{
- domain::{self, behaviour::Conversion, types as domain_types},
+ domain::{self, behaviour::Conversion},
storage,
},
};
@@ -780,7 +780,10 @@ mod merchant_connector_account_cache_tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
async fn test_connector_profile_id_cache() {
- let db = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let db = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create Mock store");
let redis_conn = db.get_redis_conn().unwrap();
let master_key = db.get_master_key();
@@ -797,7 +800,7 @@ mod merchant_connector_account_cache_tests {
db.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.into(),
- key: domain_types::encrypt(
+ key: domain::types::encrypt(
services::generate_aes256_key().unwrap().to_vec().into(),
master_key,
)
@@ -819,7 +822,7 @@ mod merchant_connector_account_cache_tests {
id: Some(1),
merchant_id: merchant_id.to_string(),
connector_name: "stripe".to_string(),
- connector_account_details: domain_types::encrypt(
+ connector_account_details: domain::types::encrypt(
serde_json::Value::default().into(),
merchant_key.key.get_inner().peek(),
)
@@ -847,15 +850,16 @@ mod merchant_connector_account_cache_tests {
.unwrap();
let find_call = || async {
- db.find_merchant_connector_account_by_profile_id_connector_name(
- profile_id,
- &mca.connector_name,
- &merchant_key,
+ Conversion::convert(
+ db.find_merchant_connector_account_by_profile_id_connector_name(
+ profile_id,
+ &mca.connector_name,
+ &merchant_key,
+ )
+ .await
+ .unwrap(),
)
.await
- .unwrap()
- .convert()
- .await
.change_context(errors::StorageError::DecryptionError)
};
let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory(
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index 28d0a71a4b0..8cb93fc369b 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -149,13 +149,16 @@ mod tests {
use crate::{
db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb},
services,
- types::domain::{self, types as domain_types},
+ types::domain::{self},
};
#[allow(clippy::unwrap_used)]
#[tokio::test]
async fn test_mock_db_merchant_key_store_interface() {
- let mock_db = MockDb::new().await;
+ #[allow(clippy::expect_used)]
+ let mock_db = MockDb::new(&redis_interface::RedisSettings::default())
+ .await
+ .expect("Failed to create mock DB");
let master_key = mock_db.get_master_key();
let merchant_id = "merchant1";
@@ -163,7 +166,7 @@ mod tests {
.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.into(),
- key: domain_types::encrypt(
+ key: domain::types::encrypt(
services::generate_aes256_key().unwrap().to_vec().into(),
master_key,
)
@@ -188,7 +191,7 @@ mod tests {
.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.into(),
- key: domain_types::encrypt(
+ key: domain::types::encrypt(
services::generate_aes256_key().unwrap().to_vec().into(),
master_key,
)
diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs
deleted file mode 100644
index d8b1e20db28..00000000000
--- a/crates/router/src/db/payment_attempt.rs
+++ /dev/null
@@ -1,1051 +0,0 @@
-use api_models::enums::{Connector, PaymentMethod};
-
-use super::MockDb;
-use crate::{
- core::errors::{self, CustomResult},
- types::storage::{self as types, enums},
-};
-
-#[async_trait::async_trait]
-pub trait PaymentAttemptInterface {
- async fn insert_payment_attempt(
- &self,
- payment_attempt: types::PaymentAttemptNew,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn update_payment_attempt_with_attempt_id(
- &self,
- this: types::PaymentAttempt,
- payment_attempt: types::PaymentAttemptUpdate,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
- &self,
- connector_transaction_id: &str,
- payment_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_payment_attempt_by_merchant_id_connector_txn_id(
- &self,
- merchant_id: &str,
- connector_txn_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_payment_attempt_by_attempt_id_merchant_id(
- &self,
- attempt_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_payment_attempt_by_preprocessing_id_merchant_id(
- &self,
- preprocessing_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError>;
-
- async fn find_attempts_by_merchant_id_payment_id(
- &self,
- merchant_id: &str,
- payment_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<types::PaymentAttempt>, errors::StorageError>;
-
- async fn get_filters_for_payments(
- &self,
- pi: &[types::PaymentIntent],
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<diesel_models::payment_attempt::PaymentListFilters, errors::StorageError>;
-
- async fn get_total_count_of_filtered_payment_attempts(
- &self,
- merchant_id: &str,
- active_attempt_ids: &[String],
- connector: Option<Vec<Connector>>,
- payment_methods: Option<Vec<PaymentMethod>>,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<i64, errors::StorageError>;
-}
-
-#[cfg(not(feature = "kv_store"))]
-mod storage {
- use api_models::enums::{Connector, PaymentMethod};
- use error_stack::IntoReport;
- use storage_impl::DataModelExt;
-
- use super::PaymentAttemptInterface;
- use crate::{
- connection,
- core::errors::{self, CustomResult},
- services::Store,
- types::storage::{enums, payment_attempt::*},
- };
-
- #[async_trait::async_trait]
- impl PaymentAttemptInterface for Store {
- async fn insert_payment_attempt(
- &self,
- payment_attempt: PaymentAttemptNew,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- payment_attempt
- .insert(&conn)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn update_payment_attempt_with_attempt_id(
- &self,
- this: PaymentAttempt,
- payment_attempt: PaymentAttemptUpdate,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- this.update_with_attempt_id(&conn, payment_attempt)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
- &self,
- connector_transaction_id: &str,
- payment_id: &str,
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id(
- &conn,
- connector_transaction_id,
- payment_id,
- merchant_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id(
- &conn,
- payment_id,
- merchant_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_by_merchant_id_connector_txn_id(
- &self,
- merchant_id: &str,
- connector_txn_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_merchant_id_connector_txn_id(
- &conn,
- merchant_id,
- connector_txn_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
-
- PaymentAttempt::find_by_payment_id_merchant_id_attempt_id(
- &conn,
- payment_id,
- merchant_id,
- attempt_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn get_filters_for_payments(
- &self,
- pi: &[data_models::payments::payment_intent::PaymentIntent],
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<diesel_models::payment_attempt::PaymentListFilters, errors::StorageError>
- {
- let conn = connection::pg_connection_read(self).await?;
- let intents = pi
- .iter()
- .cloned()
- .map(|pi| pi.to_storage_model())
- .collect::<Vec<diesel_models::payment_intent::PaymentIntent>>();
- PaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn get_total_count_of_filtered_payment_attempts(
- &self,
- merchant_id: &str,
- active_attempt_ids: &[String],
- connector: Option<Vec<Connector>>,
- payment_methods: Option<Vec<PaymentMethod>>,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<i64, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- let connector_strings = if let Some(connector_vec) = &connector {
- Some(
- connector_vec
- .iter()
- .map(|c| c.to_string())
- .collect::<Vec<String>>(),
- )
- } else {
- None
- };
- PaymentAttempt::get_total_count_of_attempts(
- &conn,
- merchant_id,
- active_attempt_ids,
- connector_strings,
- payment_methods,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_by_preprocessing_id_merchant_id(
- &self,
- preprocessing_id: &str,
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
-
- PaymentAttempt::find_by_merchant_id_preprocessing_id(
- &conn,
- merchant_id,
- preprocessing_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_attempts_by_merchant_id_payment_id(
- &self,
- merchant_id: &str,
- payment_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_by_attempt_id_merchant_id(
- &self,
- merchant_id: &str,
- attempt_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
-
- PaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id)
- .await
- .map_err(Into::into)
- .into_report()
- }
- }
-}
-
-#[async_trait::async_trait]
-impl PaymentAttemptInterface for MockDb {
- async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
- &self,
- _payment_id: &str,
- _merchant_id: &str,
- _attempt_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- async fn get_filters_for_payments(
- &self,
- _pi: &[data_models::payments::payment_intent::PaymentIntent],
- _merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<diesel_models::payment_attempt::PaymentListFilters, errors::StorageError>
- {
- Err(errors::StorageError::MockDbError)?
- }
-
- async fn get_total_count_of_filtered_payment_attempts(
- &self,
- _merchant_id: &str,
- _active_attempt_ids: &[String],
- _connector: Option<Vec<Connector>>,
- _payment_methods: Option<Vec<PaymentMethod>>,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<i64, errors::StorageError> {
- Err(errors::StorageError::MockDbError)?
- }
-
- async fn find_payment_attempt_by_attempt_id_merchant_id(
- &self,
- _attempt_id: &str,
- _merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- async fn find_payment_attempt_by_preprocessing_id_merchant_id(
- &self,
- _preprocessing_id: &str,
- _merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- async fn find_payment_attempt_by_merchant_id_connector_txn_id(
- &self,
- _merchant_id: &str,
- _connector_txn_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- async fn find_attempts_by_merchant_id_payment_id(
- &self,
- _merchant_id: &str,
- _payment_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<types::PaymentAttempt>, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- #[allow(clippy::panic)]
- async fn insert_payment_attempt(
- &self,
- payment_attempt: types::PaymentAttemptNew,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- let mut payment_attempts = self.payment_attempts.lock().await;
- #[allow(clippy::as_conversions)]
- let id = payment_attempts.len() as i32;
- let time = common_utils::date_time::now();
-
- let payment_attempt = types::PaymentAttempt {
- id,
- payment_id: payment_attempt.payment_id,
- merchant_id: payment_attempt.merchant_id,
- attempt_id: payment_attempt.attempt_id,
- status: payment_attempt.status,
- amount: payment_attempt.amount,
- currency: payment_attempt.currency,
- save_to_locker: payment_attempt.save_to_locker,
- connector: payment_attempt.connector,
- error_message: payment_attempt.error_message,
- offer_amount: payment_attempt.offer_amount,
- surcharge_amount: payment_attempt.surcharge_amount,
- tax_amount: payment_attempt.tax_amount,
- payment_method_id: payment_attempt.payment_method_id,
- payment_method: payment_attempt.payment_method,
- connector_transaction_id: None,
- capture_method: payment_attempt.capture_method,
- capture_on: payment_attempt.capture_on,
- confirm: payment_attempt.confirm,
- authentication_type: payment_attempt.authentication_type,
- created_at: payment_attempt.created_at.unwrap_or(time),
- modified_at: payment_attempt.modified_at.unwrap_or(time),
- last_synced: payment_attempt.last_synced,
- cancellation_reason: payment_attempt.cancellation_reason,
- amount_to_capture: payment_attempt.amount_to_capture,
- mandate_id: None,
- browser_info: None,
- payment_token: None,
- error_code: payment_attempt.error_code,
- connector_metadata: None,
- payment_experience: payment_attempt.payment_experience,
- payment_method_type: payment_attempt.payment_method_type,
- payment_method_data: payment_attempt.payment_method_data,
- business_sub_label: payment_attempt.business_sub_label,
- straight_through_algorithm: payment_attempt.straight_through_algorithm,
- mandate_details: payment_attempt.mandate_details,
- preprocessing_step_id: payment_attempt.preprocessing_step_id,
- error_reason: payment_attempt.error_reason,
- multiple_capture_count: payment_attempt.multiple_capture_count,
- connector_response_reference_id: None,
- };
- payment_attempts.push(payment_attempt.clone());
- Ok(payment_attempt)
- }
-
- // safety: only used for testing
- #[allow(clippy::unwrap_used)]
- async fn update_payment_attempt_with_attempt_id(
- &self,
- this: types::PaymentAttempt,
- payment_attempt: types::PaymentAttemptUpdate,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- let mut payment_attempts = self.payment_attempts.lock().await;
-
- let item = payment_attempts
- .iter_mut()
- .find(|item| item.attempt_id == this.attempt_id)
- .unwrap();
-
- *item = payment_attempt.apply_changeset(this);
-
- Ok(item.clone())
- }
-
- async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
- &self,
- _connector_transaction_id: &str,
- _payment_id: &str,
- _merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError)?
- }
-
- // safety: only used for testing
- #[allow(clippy::unwrap_used)]
- async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
- let payment_attempts = self.payment_attempts.lock().await;
-
- Ok(payment_attempts
- .iter()
- .find(|payment_attempt| {
- payment_attempt.payment_id == payment_id
- && payment_attempt.merchant_id == merchant_id
- })
- .cloned()
- .unwrap())
- }
-}
-
-#[cfg(feature = "kv_store")]
-mod storage {
- use common_utils::date_time;
- use diesel_models::reverse_lookup::ReverseLookup;
- use error_stack::{IntoReport, ResultExt};
- use redis_interface::HsetnxReply;
- use storage_impl::{redis::kv_store::RedisConnInterface, DataModelExt};
-
- use super::PaymentAttemptInterface;
- use crate::{
- connection,
- core::errors::{self, CustomResult},
- db::reverse_lookup::ReverseLookupInterface,
- services::Store,
- types::storage::{enums, kv, payment_attempt::*, ReverseLookupNew},
- utils::db_utils,
- };
-
- #[async_trait::async_trait]
- impl PaymentAttemptInterface for Store {
- async fn insert_payment_attempt(
- &self,
- payment_attempt: PaymentAttemptNew,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => {
- let conn = connection::pg_connection_write(self).await?;
- payment_attempt
- .insert(&conn)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- enums::MerchantStorageScheme::RedisKv => {
- let key = format!(
- "{}_{}",
- payment_attempt.merchant_id, payment_attempt.payment_id
- );
-
- let created_attempt = PaymentAttempt {
- id: Default::default(),
- payment_id: payment_attempt.payment_id.clone(),
- merchant_id: payment_attempt.merchant_id.clone(),
- attempt_id: payment_attempt.attempt_id.clone(),
- status: payment_attempt.status,
- amount: payment_attempt.amount,
- currency: payment_attempt.currency,
- save_to_locker: payment_attempt.save_to_locker,
- connector: payment_attempt.connector.clone(),
- error_message: payment_attempt.error_message.clone(),
- offer_amount: payment_attempt.offer_amount,
- surcharge_amount: payment_attempt.surcharge_amount,
- tax_amount: payment_attempt.tax_amount,
- payment_method_id: payment_attempt.payment_method_id.clone(),
- payment_method: payment_attempt.payment_method,
- connector_transaction_id: None,
- capture_method: payment_attempt.capture_method,
- capture_on: payment_attempt.capture_on,
- confirm: payment_attempt.confirm,
- authentication_type: payment_attempt.authentication_type,
- created_at: payment_attempt.created_at.unwrap_or_else(date_time::now),
- modified_at: payment_attempt.created_at.unwrap_or_else(date_time::now),
- last_synced: payment_attempt.last_synced,
- amount_to_capture: payment_attempt.amount_to_capture,
- cancellation_reason: payment_attempt.cancellation_reason.clone(),
- mandate_id: payment_attempt.mandate_id.clone(),
- browser_info: payment_attempt.browser_info.clone(),
- payment_token: payment_attempt.payment_token.clone(),
- error_code: payment_attempt.error_code.clone(),
- connector_metadata: payment_attempt.connector_metadata.clone(),
- payment_experience: payment_attempt.payment_experience,
- payment_method_type: payment_attempt.payment_method_type,
- payment_method_data: payment_attempt.payment_method_data.clone(),
- business_sub_label: payment_attempt.business_sub_label.clone(),
- straight_through_algorithm: payment_attempt
- .straight_through_algorithm
- .clone(),
- mandate_details: payment_attempt.mandate_details.clone(),
- preprocessing_step_id: payment_attempt.preprocessing_step_id.clone(),
- error_reason: payment_attempt.error_reason.clone(),
- multiple_capture_count: payment_attempt.multiple_capture_count,
- connector_response_reference_id: None,
- };
-
- let field = format!("pa_{}", created_attempt.attempt_id);
- match self
- .get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_attempt)
- .await
- {
- Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
- entity: "payment attempt",
- key: Some(key),
- })
- .into_report(),
- Ok(HsetnxReply::KeySet) => {
- let conn = connection::pg_connection_write(self).await?;
-
- //Reverse lookup for attempt_id
- ReverseLookupNew {
- lookup_id: format!(
- "{}_{}",
- &created_attempt.merchant_id, &created_attempt.attempt_id,
- ),
- pk_id: key,
- sk_id: field,
- source: "payment_attempt".to_string(),
- }
- .insert(&conn)
- .await
- .map_err(Into::<errors::StorageError>::into)
- .into_report()?;
-
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Insert {
- insertable: kv::Insertable::PaymentAttempt(payment_attempt),
- },
- };
- self.push_to_drainer_stream::<PaymentAttempt>(
- redis_entry,
- crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
- merchant_id: &created_attempt.merchant_id,
- payment_id: &created_attempt.payment_id,
- }
- )
- .await.change_context(errors::StorageError::KVError)?;
- Ok(created_attempt)
- }
- Err(error) => Err(error.change_context(errors::StorageError::KVError)),
- }
- }
- }
- }
-
- async fn update_payment_attempt_with_attempt_id(
- &self,
- this: PaymentAttempt,
- payment_attempt: PaymentAttemptUpdate,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => {
- let conn = connection::pg_connection_write(self).await?;
- this.update_with_attempt_id(&conn, payment_attempt)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- enums::MerchantStorageScheme::RedisKv => {
- let key = format!("{}_{}", this.merchant_id, this.payment_id);
- let old_connector_transaction_id = &this.connector_transaction_id;
- let old_preprocessing_id = &this.preprocessing_step_id;
- let updated_attempt = payment_attempt.clone().apply_changeset(this.clone());
- // Check for database presence as well Maybe use a read replica here ?
- let redis_value = serde_json::to_string(&updated_attempt)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
- let field = format!("pa_{}", updated_attempt.attempt_id);
- let updated_attempt = self
- .get_redis_conn()
- .change_context(errors::StorageError::KVError)?
- .set_hash_fields(&key, (&field, &redis_value))
- .await
- .map(|_| updated_attempt)
- .change_context(errors::StorageError::KVError)?;
-
- match (
- old_connector_transaction_id,
- &updated_attempt.connector_transaction_id,
- ) {
- (None, Some(connector_transaction_id)) => {
- add_connector_txn_id_to_reverse_lookup(
- self,
- key.as_str(),
- this.merchant_id.as_str(),
- updated_attempt.attempt_id.as_str(),
- connector_transaction_id.as_str(),
- )
- .await?;
- }
- (Some(old_connector_transaction_id), Some(connector_transaction_id)) => {
- if old_connector_transaction_id.ne(connector_transaction_id) {
- add_connector_txn_id_to_reverse_lookup(
- self,
- key.as_str(),
- this.merchant_id.as_str(),
- updated_attempt.attempt_id.as_str(),
- connector_transaction_id.as_str(),
- )
- .await?;
- }
- }
- (_, _) => {}
- }
-
- match (old_preprocessing_id, &updated_attempt.preprocessing_step_id) {
- (None, Some(preprocessing_id)) => {
- add_preprocessing_id_to_reverse_lookup(
- self,
- key.as_str(),
- this.merchant_id.as_str(),
- updated_attempt.attempt_id.as_str(),
- preprocessing_id.as_str(),
- )
- .await?;
- }
- (Some(old_preprocessing_id), Some(preprocessing_id)) => {
- if old_preprocessing_id.ne(preprocessing_id) {
- add_preprocessing_id_to_reverse_lookup(
- self,
- key.as_str(),
- this.merchant_id.as_str(),
- updated_attempt.attempt_id.as_str(),
- preprocessing_id.as_str(),
- )
- .await?;
- }
- }
- (_, _) => {}
- }
-
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: kv::Updateable::PaymentAttemptUpdate(
- kv::PaymentAttemptUpdateMems {
- orig: this,
- update_data: payment_attempt,
- },
- ),
- },
- };
- self.push_to_drainer_stream::<PaymentAttempt>(
- redis_entry,
- crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
- merchant_id: &updated_attempt.merchant_id,
- payment_id: &updated_attempt.payment_id,
- },
- )
- .await
- .change_context(errors::StorageError::KVError)?;
- Ok(updated_attempt)
- }
- }
- }
-
- async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
- &self,
- connector_transaction_id: &str,
- payment_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let database_call = || async {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id(
- &conn,
- connector_transaction_id,
- payment_id,
- merchant_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- };
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => database_call().await,
- enums::MerchantStorageScheme::RedisKv => {
- // We assume that PaymentAttempt <=> PaymentIntent is a one-to-one relation for now
- let lookup_id = format!("{merchant_id}_{connector_transaction_id}");
- let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
- let key = &lookup.pk_id;
-
- db_utils::try_redis_get_else_try_database_get(
- self.get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
- database_call,
- )
- .await
- }
- }
- }
-
- async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id(
- &conn,
- payment_id,
- merchant_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn find_payment_attempt_by_merchant_id_connector_txn_id(
- &self,
- merchant_id: &str,
- connector_txn_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let database_call = || async {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_merchant_id_connector_txn_id(
- &conn,
- merchant_id,
- connector_txn_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- };
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => database_call().await,
-
- enums::MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("{merchant_id}_{connector_txn_id}");
- let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
-
- let key = &lookup.pk_id;
- db_utils::try_redis_get_else_try_database_get(
- self.get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
- database_call,
- )
- .await
- }
- }
- }
-
- async fn find_payment_attempt_by_attempt_id_merchant_id(
- &self,
- attempt_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let database_call = || async {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id)
- .await
- .map_err(Into::into)
- .into_report()
- };
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => database_call().await,
-
- enums::MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("{merchant_id}_{attempt_id}");
- let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
- let key = &lookup.pk_id;
- db_utils::try_redis_get_else_try_database_get(
- self.get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
- database_call,
- )
- .await
- }
- }
- }
-
- async fn find_payment_attempt_by_preprocessing_id_merchant_id(
- &self,
- preprocessing_id: &str,
- merchant_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let database_call = || async {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_merchant_id_preprocessing_id(
- &conn,
- merchant_id,
- preprocessing_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- };
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => database_call().await,
- enums::MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("{merchant_id}_{preprocessing_id}");
- let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
- let key = &lookup.pk_id;
-
- db_utils::try_redis_get_else_try_database_get(
- self.get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
- database_call,
- )
- .await
- }
- }
- }
-
- async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- attempt_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let database_call = || async {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_payment_id_merchant_id_attempt_id(
- &conn,
- payment_id,
- merchant_id,
- attempt_id,
- )
- .await
- .map_err(Into::into)
- .into_report()
- };
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => database_call().await,
-
- enums::MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("{merchant_id}_{attempt_id}");
- let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
- let key = &lookup.pk_id;
- db_utils::try_redis_get_else_try_database_get(
- self.get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
- database_call,
- )
- .await
- }
- }
- }
-
- async fn find_attempts_by_merchant_id_payment_id(
- &self,
- merchant_id: &str,
- payment_id: &str,
- storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> {
- match storage_scheme {
- enums::MerchantStorageScheme::PostgresOnly => {
- let conn = connection::pg_connection_read(self).await?;
- PaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
- .await
- .map_err(Into::into)
- .into_report()
- }
- enums::MerchantStorageScheme::RedisKv => {
- let key = format!("{merchant_id}_{payment_id}");
- let lookup = self.get_lookup_by_lookup_id(&key).await?;
-
- let pattern = db_utils::generate_hscan_pattern_for_attempt(&lookup.sk_id);
-
- self.get_redis_conn()
- .map_err(Into::<errors::StorageError>::into)?
- .hscan_and_deserialize(&key, &pattern, None)
- .await
- .change_context(errors::StorageError::KVError)
- }
- }
- }
-
- async fn get_filters_for_payments(
- &self,
- pi: &[data_models::payments::payment_intent::PaymentIntent],
- merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<diesel_models::payment_attempt::PaymentListFilters, errors::StorageError>
- {
- let conn = connection::pg_connection_read(self).await?;
- let intents = pi
- .iter()
- .cloned()
- .map(|pi| pi.to_storage_model())
- .collect::<Vec<diesel_models::payment_intent::PaymentIntent>>();
- PaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id)
- .await
- .map_err(Into::into)
- .into_report()
- }
-
- async fn get_total_count_of_filtered_payment_attempts(
- &self,
- merchant_id: &str,
- active_attempt_ids: &[String],
- connector: Option<Vec<api_models::enums::Connector>>,
- payment_methods: Option<Vec<api_models::enums::PaymentMethod>>,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<i64, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
-
- let connector_strings = connector.as_ref().map(|connector_vec| {
- connector_vec
- .iter()
- .map(|c| c.to_string())
- .collect::<Vec<String>>()
- });
-
- PaymentAttempt::get_total_count_of_attempts(
- &conn,
- merchant_id,
- active_attempt_ids,
- connector_strings,
- payment_methods,
- )
- .await
- .map_err(Into::into)
- .into_report()
- }
- }
-
- #[inline]
- async fn add_connector_txn_id_to_reverse_lookup(
- store: &Store,
- key: &str,
- merchant_id: &str,
- updated_attempt_attempt_id: &str,
- connector_transaction_id: &str,
- ) -> CustomResult<ReverseLookup, errors::StorageError> {
- let conn = connection::pg_connection_write(store).await?;
- let field = format!("pa_{}", updated_attempt_attempt_id);
- ReverseLookupNew {
- lookup_id: format!("{}_{}", merchant_id, connector_transaction_id),
- pk_id: key.to_owned(),
- sk_id: field.clone(),
- source: "payment_attempt".to_string(),
- }
- .insert(&conn)
- .await
- .map_err(Into::<errors::StorageError>::into)
- .into_report()
- }
-
- #[inline]
- async fn add_preprocessing_id_to_reverse_lookup(
- store: &Store,
- key: &str,
- merchant_id: &str,
- updated_attempt_attempt_id: &str,
- preprocessing_id: &str,
- ) -> CustomResult<ReverseLookup, errors::StorageError> {
- let conn = connection::pg_connection_write(store).await?;
- let field = format!("pa_{}", updated_attempt_attempt_id);
- ReverseLookupNew {
- lookup_id: format!("{}_{}", merchant_id, preprocessing_id),
- pk_id: key.to_owned(),
- sk_id: field.clone(),
- source: "payment_attempt".to_string(),
- }
- .insert(&conn)
- .await
- .map_err(Into::<errors::StorageError>::into)
- .into_report()
- }
-}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index fa87aedaa5e..a89de10f391 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -89,7 +89,12 @@ impl AppState {
.await
.expect("Failed to create store"),
),
- StorageImpl::Mock => Box::new(MockDb::new().await),
+ #[allow(clippy::expect_used)]
+ StorageImpl::Mock => Box::new(
+ MockDb::new(&conf.redis)
+ .await
+ .expect("Failed to create mock store"),
+ ),
};
#[cfg(feature = "kms")]
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index af989ac2f58..4c1c3d8c3a5 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -18,6 +18,7 @@ pub use api_models::{
payouts as payout_types,
};
use common_utils::{pii, pii::Email};
+use data_models::mandates::MandateData;
use error_stack::{IntoReport, ResultExt};
use masking::Secret;
@@ -350,7 +351,7 @@ pub struct PaymentsAuthorizeData {
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
- pub setup_mandate_details: Option<payments::MandateData>,
+ pub setup_mandate_details: Option<MandateData>,
pub browser_info: Option<BrowserInformation>,
pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
pub order_category: Option<String>,
@@ -411,7 +412,7 @@ pub struct PaymentsPreProcessingData {
pub email: Option<Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
- pub setup_mandate_details: Option<payments::MandateData>,
+ pub setup_mandate_details: Option<MandateData>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
pub router_return_url: Option<String>,
@@ -432,7 +433,7 @@ pub struct CompleteAuthorizeData {
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
- pub setup_mandate_details: Option<payments::MandateData>,
+ pub setup_mandate_details: Option<MandateData>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
@@ -502,7 +503,7 @@ pub struct VerifyRequestData {
pub mandate_id: Option<api_models::payments::MandateIds>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
- pub setup_mandate_details: Option<payments::MandateData>,
+ pub setup_mandate_details: Option<MandateData>,
pub router_return_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub email: Option<Email>,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index b2e1617e5ea..23c9f850dab 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -41,7 +41,7 @@ pub trait ConnectorAccessToken:
pub trait ConnectorTransactionId: ConnectorCommon + Sync {
fn connector_transaction_id(
&self,
- payment_attempt: diesel_models::payment_attempt::PaymentAttempt,
+ payment_attempt: data_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, errors::ApiErrorResponse> {
Ok(payment_attempt.connector_transaction_id)
}
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index f266e67af1c..eecaac6ced6 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -1,19 +1,17 @@
pub use api_models::payments::{
AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card,
- CryptoData, CustomerAcceptance, HeaderPayload, MandateData, MandateTransactionType,
- MandateType, MandateValidationFields, NextActionType, OnlineMandate, PayLaterData,
- PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters,
- PaymentListResponse, PaymentListResponseV2, PaymentMethodData, PaymentMethodDataResponse,
- PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest,
- PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsRedirectRequest,
+ CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData,
+ MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate,
+ PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints,
+ PaymentListFilters, PaymentListResponse, PaymentListResponseV2, PaymentMethodData,
+ PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials,
+ PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsRedirectRequest,
PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse,
PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse,
PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken,
TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData,
};
use error_stack::{IntoReport, ResultExt};
-use masking::PeekInterface;
-use time::PrimitiveDateTime;
use crate::{
core::errors,
@@ -35,29 +33,6 @@ impl PaymentsRequestExt for PaymentsRequest {
}
}
-pub(crate) trait CustomerAcceptanceExt {
- fn get_ip_address(&self) -> Option<String>;
- fn get_user_agent(&self) -> Option<String>;
- fn get_accepted_at(&self) -> PrimitiveDateTime;
-}
-
-impl CustomerAcceptanceExt for CustomerAcceptance {
- fn get_ip_address(&self) -> Option<String> {
- self.online
- .as_ref()
- .and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned()))
- }
-
- fn get_user_agent(&self) -> Option<String> {
- self.online.as_ref().map(|data| data.user_agent.clone())
- }
-
- fn get_accepted_at(&self) -> PrimitiveDateTime {
- self.accepted_at
- .unwrap_or_else(common_utils::date_time::now)
- }
-}
-
impl super::Router for PaymentsRequest {}
// Core related api layer.
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 37e1c14ae42..9995f7cce89 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -29,14 +29,20 @@ pub mod payouts;
mod query;
pub mod refund;
-pub use data_models::payments::payment_intent::{
- PaymentIntent, PaymentIntentNew, PaymentIntentUpdate,
+pub use data_models::payments::{
+ payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
+ payment_intent::{PaymentIntent, PaymentIntentNew, PaymentIntentUpdate},
};
pub use self::{
address::*, api_keys::*, capture::*, cards_info::*, configs::*, connector_response::*,
customers::*, dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*,
- merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_attempt::*,
- payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*,
- reverse_lookup::*,
+ merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_method::*,
+ payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*,
};
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct RoutingData {
+ pub routed_through: Option<String>,
+ pub algorithm: Option<api_models::admin::StraightThroughAlgorithm>,
+}
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index c7631282b28..1a9af97329e 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -1,17 +1,11 @@
-pub use diesel_models::payment_attempt::{
- PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal,
+pub use data_models::payments::payment_attempt::{
+ PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate,
};
use diesel_models::{capture::CaptureNew, enums};
use error_stack::ResultExt;
use crate::{core::errors, errors::RouterResult, utils::OptionExt};
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct RoutingData {
- pub routed_through: Option<String>,
- pub algorithm: Option<api_models::admin::StraightThroughAlgorithm>,
-}
-
pub trait PaymentAttemptExt {
fn make_new_capture(
&self,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index c2a10abd672..9a0e0a385e2 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -180,6 +180,58 @@ 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 {
+ fn foreign_from(d: api_models::payments::MandateData) -> Self {
+ Self {
+ customer_acceptance: d.customer_acceptance.map(|d| {
+ data_models::mandates::CustomerAcceptance {
+ acceptance_type: match d.acceptance_type {
+ api_models::payments::AcceptanceType::Online => {
+ data_models::mandates::AcceptanceType::Online
+ }
+ api_models::payments::AcceptanceType::Offline => {
+ data_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,
+ }),
+ }
+ }),
+ 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 {
+ amount: i.amount,
+ currency: i.currency,
+ start_date: i.start_date,
+ end_date: i.end_date,
+ metadata: i.metadata,
+ },
+ ))
+ }
+ api_models::payments::MandateType::SingleUse(i) => {
+ data_models::mandates::MandateDataType::SingleUse(
+ data_models::mandates::MandateAmountData {
+ amount: i.amount,
+ currency: i.currency,
+ start_date: i.start_date,
+ end_date: i.end_date,
+ metadata: i.metadata,
+ },
+ )
+ }
+ api_models::payments::MandateType::MultiUse(None) => {
+ data_models::mandates::MandateDataType::MultiUse(None)
+ }
+ }),
+ }
+ }
+}
+
impl ForeignFrom<api_models::payments::MandateAmountData> for storage_enums::MandateAmountData {
fn foreign_from(from: api_models::payments::MandateAmountData) -> Self {
Self {
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 2452676378f..4ac092125ac 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -15,6 +15,7 @@ pub use common_utils::{
fp_utils::when,
validation::validate_email,
};
+use data_models::payments::payment_intent::PaymentIntent;
use error_stack::{IntoReport, ResultExt};
use image::Luma;
use nanoid::nanoid;
@@ -23,17 +24,14 @@ use serde::de::DeserializeOwned;
use serde_json::Value;
use uuid::Uuid;
-pub use self::{
- ext_traits::{OptionExt, ValidateCall},
- storage::PaymentIntent,
-};
+pub use self::ext_traits::{OptionExt, ValidateCall};
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult, StorageErrorExt},
db::StorageInterface,
logger,
routes::metrics,
- types::{self, domain, storage},
+ types::{self, domain},
};
pub mod error_parser {
diff --git a/crates/router/src/utils/db_utils.rs b/crates/router/src/utils/db_utils.rs
index c169de293d6..febc226c020 100644
--- a/crates/router/src/utils/db_utils.rs
+++ b/crates/router/src/utils/db_utils.rs
@@ -1,6 +1,5 @@
use crate::{core::errors, routes::metrics};
-#[cfg(feature = "kv_store")]
/// Generates hscan field pattern. Suppose the field is pa_1234_ref_1211 it will generate
/// pa_1234_ref_*
pub fn generate_hscan_pattern_for_refund(sk: &str) -> String {
@@ -11,17 +10,6 @@ pub fn generate_hscan_pattern_for_refund(sk: &str) -> String {
.join("_")
}
-#[cfg(feature = "kv_store")]
-/// Generates hscan field pattern. Suppose the field is pa_1234 it will generate
-/// pa_*
-pub fn generate_hscan_pattern_for_attempt(sk: &str) -> String {
- sk.split('_')
- .take(1)
- .chain(["*"])
- .collect::<Vec<&str>>()
- .join("_")
-}
-
// The first argument should be a future while the second argument should be a closure that returns a future for a database call
pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(
redis_fut: RFut,
diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs
index 9cabdf77976..728c146a64e 100644
--- a/crates/scheduler/src/db/process_tracker.rs
+++ b/crates/scheduler/src/db/process_tracker.rs
@@ -3,7 +3,7 @@ pub use diesel_models as storage;
use diesel_models::enums as storage_enums;
use error_stack::{IntoReport, ResultExt};
use serde::Serialize;
-use storage_impl::{connection, errors, MockDb};
+use storage_impl::{connection, errors, mock_db::MockDb};
use time::PrimitiveDateTime;
use crate::{errors as sch_errors, metrics, scheduler::Store, SchedulerInterface};
diff --git a/crates/scheduler/src/db/queue.rs b/crates/scheduler/src/db/queue.rs
index 870b2b8179a..2c02b405d81 100644
--- a/crates/scheduler/src/db/queue.rs
+++ b/crates/scheduler/src/db/queue.rs
@@ -2,7 +2,7 @@ use common_utils::errors::CustomResult;
use diesel_models::process_tracker as storage;
use redis_interface::{errors::RedisError, RedisEntryId, SetnxReply};
use router_env::logger;
-use storage_impl::{redis::kv_store::RedisConnInterface, MockDb};
+use storage_impl::{mock_db::MockDb, redis::kv_store::RedisConnInterface};
use crate::{errors::ProcessTrackerError, scheduler::Store};
diff --git a/crates/scheduler/src/scheduler.rs b/crates/scheduler/src/scheduler.rs
index 15757c6e778..273f10819f8 100644
--- a/crates/scheduler/src/scheduler.rs
+++ b/crates/scheduler/src/scheduler.rs
@@ -1,9 +1,9 @@
use std::sync::Arc;
use common_utils::errors::CustomResult;
+use storage_impl::mock_db::MockDb;
#[cfg(feature = "kv_store")]
use storage_impl::KVRouterStore;
-use storage_impl::MockDb;
#[cfg(not(feature = "kv_store"))]
use storage_impl::RouterStore;
use tokio::sync::mpsc;
diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml
index 778277523ac..2226baa5c3b 100644
--- a/crates/storage_impl/Cargo.toml
+++ b/crates/storage_impl/Cargo.toml
@@ -42,6 +42,7 @@ mime = "0.3.17"
moka = { version = "0.11.3", features = ["future"] }
once_cell = "1.18.0"
ring = "0.16.20"
-serde = { version = "1.0.163", features = ["derive"] }
thiserror = "1.0.40"
tokio = { version = "1.28.2", features = ["rt-multi-thread"] }
+serde = { version = "1.0.185", features = ["derive"] }
+serde_json = "1.0.105"
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 5ff4d000b85..a7bc9e13cf0 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -1,26 +1,24 @@
use std::sync::Arc;
-use common_utils::errors::CustomResult;
-use data_models::{
- errors::{StorageError, StorageResult},
- payments::payment_intent::PaymentIntent,
-};
+use data_models::errors::{StorageError, StorageResult};
use diesel_models::{self as store};
use error_stack::ResultExt;
-use futures::lock::Mutex;
use masking::StrongSecret;
use redis::{kv_store::RedisConnInterface, RedisStore};
pub mod config;
pub mod connection;
pub mod database;
pub mod errors;
+mod lookup;
pub mod metrics;
+pub mod mock_db;
pub mod payments;
pub mod redis;
pub mod refund;
mod utils;
use database::store::PgPool;
+pub use mock_db::MockDb;
use redis_interface::errors::RedisError;
pub use crate::database::store::DatabaseStore;
@@ -168,6 +166,7 @@ impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> {
self.router_store.get_redis_conn()
}
}
+
impl<T: DatabaseStore> KVRouterStore<T> {
pub fn from_store(
store: RouterStore<T>,
@@ -214,60 +213,6 @@ impl<T: DatabaseStore> KVRouterStore<T> {
}
}
-#[derive(Clone)]
-pub struct MockDb {
- pub addresses: Arc<Mutex<Vec<store::Address>>>,
- pub configs: Arc<Mutex<Vec<store::Config>>>,
- pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>,
- pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>,
- pub payment_attempts: Arc<Mutex<Vec<store::PaymentAttempt>>>,
- pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>,
- pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>,
- pub customers: Arc<Mutex<Vec<store::Customer>>>,
- pub refunds: Arc<Mutex<Vec<store::Refund>>>,
- pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>,
- pub connector_response: Arc<Mutex<Vec<store::ConnectorResponse>>>,
- // pub redis: Arc<redis_interface::RedisConnectionPool>,
- pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,
- pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,
- pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>,
- pub events: Arc<Mutex<Vec<store::Event>>>,
- 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>>>,
-}
-
-impl MockDb {
- pub async fn new() -> Self {
- Self {
- addresses: Default::default(),
- configs: Default::default(),
- merchant_accounts: Default::default(),
- merchant_connector_accounts: Default::default(),
- payment_attempts: Default::default(),
- payment_intents: Default::default(),
- payment_methods: Default::default(),
- customers: Default::default(),
- refunds: Default::default(),
- processes: Default::default(),
- connector_response: Default::default(),
- // redis: Arc::new(crate::connection::redis_connection(&redis).await),
- api_keys: Default::default(),
- ephemeral_keys: Default::default(),
- cards_info: Default::default(),
- events: Default::default(),
- disputes: Default::default(),
- lockers: Default::default(),
- mandates: Default::default(),
- captures: Default::default(),
- merchant_key_store: Default::default(),
- business_profiles: Default::default(),
- }
- }
-}
// TODO: This should not be used beyond this crate
// Remove the pub modified once StorageScheme usage is completed
pub trait DataModelExt {
@@ -294,14 +239,6 @@ impl DataModelExt for data_models::MerchantStorageScheme {
}
}
-impl RedisConnInterface for MockDb {
- fn get_redis_conn(
- &self,
- ) -> Result<Arc<redis_interface::RedisConnectionPool>, error_stack::Report<RedisError>> {
- Err(RedisError::RedisConnectionError.into())
- }
-}
-
pub(crate) fn diesel_error_to_data_error(
diesel_error: &diesel_models::errors::DatabaseError,
) -> StorageError {
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
new file mode 100644
index 00000000000..e6ea1ac8bf6
--- /dev/null
+++ b/crates/storage_impl/src/lookup.rs
@@ -0,0 +1,72 @@
+use common_utils::errors::CustomResult;
+use data_models::errors;
+use diesel_models::reverse_lookup::{
+ ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew,
+};
+use error_stack::{IntoReport, ResultExt};
+
+use crate::{redis::cache::get_or_populate_redis, DatabaseStore, KVRouterStore, RouterStore};
+
+#[async_trait::async_trait]
+pub trait ReverseLookupInterface {
+ async fn insert_reverse_lookup(
+ &self,
+ _new: DieselReverseLookupNew,
+ ) -> CustomResult<DieselReverseLookup, errors::StorageError>;
+ async fn get_lookup_by_lookup_id(
+ &self,
+ _id: &str,
+ ) -> CustomResult<DieselReverseLookup, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> {
+ async fn insert_reverse_lookup(
+ &self,
+ new: DieselReverseLookupNew,
+ ) -> CustomResult<DieselReverseLookup, errors::StorageError> {
+ let conn = self
+ .get_master_pool()
+ .get()
+ .await
+ .into_report()
+ .change_context(errors::StorageError::DatabaseConnectionError)?;
+ new.insert(&conn).await.map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ }
+
+ async fn get_lookup_by_lookup_id(
+ &self,
+ id: &str,
+ ) -> CustomResult<DieselReverseLookup, errors::StorageError> {
+ let database_call = || async {
+ let conn = crate::utils::pg_connection_read(self).await?;
+ DieselReverseLookup::find_by_lookup_id(id, &conn)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ };
+ get_or_populate_redis(self, id, database_call).await
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
+ async fn insert_reverse_lookup(
+ &self,
+ new: DieselReverseLookupNew,
+ ) -> CustomResult<DieselReverseLookup, errors::StorageError> {
+ self.router_store.insert_reverse_lookup(new).await
+ }
+
+ async fn get_lookup_by_lookup_id(
+ &self,
+ id: &str,
+ ) -> CustomResult<DieselReverseLookup, errors::StorageError> {
+ self.router_store.get_lookup_by_lookup_id(id).await
+ }
+}
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
new file mode 100644
index 00000000000..81242af9c77
--- /dev/null
+++ b/crates/storage_impl/src/mock_db.rs
@@ -0,0 +1,75 @@
+use std::sync::Arc;
+
+use data_models::{
+ errors::StorageError,
+ payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent},
+};
+use diesel_models::{self as store};
+use error_stack::ResultExt;
+use futures::lock::Mutex;
+use redis_interface::RedisSettings;
+
+use crate::redis::RedisStore;
+
+pub mod payment_attempt;
+pub mod payment_intent;
+pub mod redis_conn;
+
+#[derive(Clone)]
+pub struct MockDb {
+ pub addresses: Arc<Mutex<Vec<store::Address>>>,
+ pub configs: Arc<Mutex<Vec<store::Config>>>,
+ pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>,
+ pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>,
+ pub payment_attempts: Arc<Mutex<Vec<PaymentAttempt>>>,
+ pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>,
+ pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>,
+ pub customers: Arc<Mutex<Vec<store::Customer>>>,
+ pub refunds: Arc<Mutex<Vec<store::Refund>>>,
+ pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>,
+ pub connector_response: Arc<Mutex<Vec<store::ConnectorResponse>>>,
+ pub redis: Arc<RedisStore>,
+ pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,
+ pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,
+ pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>,
+ pub events: Arc<Mutex<Vec<store::Event>>>,
+ 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>>>,
+}
+
+impl MockDb {
+ pub async fn new(redis: &RedisSettings) -> error_stack::Result<Self, StorageError> {
+ Ok(Self {
+ addresses: Default::default(),
+ configs: Default::default(),
+ merchant_accounts: Default::default(),
+ merchant_connector_accounts: Default::default(),
+ payment_attempts: Default::default(),
+ payment_intents: Default::default(),
+ payment_methods: Default::default(),
+ customers: Default::default(),
+ refunds: Default::default(),
+ processes: Default::default(),
+ connector_response: Default::default(),
+ redis: Arc::new(
+ RedisStore::new(redis)
+ .await
+ .change_context(StorageError::InitializationError)?,
+ ),
+ api_keys: Default::default(),
+ ephemeral_keys: Default::default(),
+ cards_info: Default::default(),
+ events: Default::default(),
+ disputes: Default::default(),
+ lockers: Default::default(),
+ mandates: Default::default(),
+ captures: Default::default(),
+ merchant_key_store: Default::default(),
+ business_profiles: Default::default(),
+ })
+ }
+}
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
new file mode 100644
index 00000000000..32b33d59674
--- /dev/null
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -0,0 +1,199 @@
+use api_models::enums::{Connector, PaymentMethod};
+use common_utils::errors::CustomResult;
+use data_models::{
+ errors::StorageError,
+ payments::payment_attempt::{
+ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
+ },
+ MerchantStorageScheme,
+};
+
+use super::MockDb;
+use crate::DataModelExt;
+
+#[async_trait::async_trait]
+impl PaymentAttemptInterface for MockDb {
+ async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
+ &self,
+ _payment_id: &str,
+ _merchant_id: &str,
+ _attempt_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ async fn get_filters_for_payments(
+ &self,
+ _pi: &[data_models::payments::payment_intent::PaymentIntent],
+ _merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<data_models::payments::payment_attempt::PaymentListFilters, StorageError>
+ {
+ Err(StorageError::MockDbError)?
+ }
+
+ async fn get_total_count_of_filtered_payment_attempts(
+ &self,
+ _merchant_id: &str,
+ _active_attempt_ids: &[String],
+ _connector: Option<Vec<Connector>>,
+ _payment_methods: Option<Vec<PaymentMethod>>,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<i64, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
+
+ async fn find_payment_attempt_by_attempt_id_merchant_id(
+ &self,
+ _attempt_id: &str,
+ _merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ async fn find_payment_attempt_by_preprocessing_id_merchant_id(
+ &self,
+ _preprocessing_id: &str,
+ _merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ async fn find_payment_attempt_by_merchant_id_connector_txn_id(
+ &self,
+ _merchant_id: &str,
+ _connector_txn_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ async fn find_attempts_by_merchant_id_payment_id(
+ &self,
+ _merchant_id: &str,
+ _payment_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ #[allow(clippy::panic)]
+ async fn insert_payment_attempt(
+ &self,
+ payment_attempt: PaymentAttemptNew,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ let mut payment_attempts = self.payment_attempts.lock().await;
+ #[allow(clippy::as_conversions)]
+ let id = payment_attempts.len() as i32;
+ let time = common_utils::date_time::now();
+
+ let payment_attempt = PaymentAttempt {
+ id,
+ payment_id: payment_attempt.payment_id,
+ merchant_id: payment_attempt.merchant_id,
+ attempt_id: payment_attempt.attempt_id,
+ status: payment_attempt.status,
+ amount: payment_attempt.amount,
+ currency: payment_attempt.currency,
+ save_to_locker: payment_attempt.save_to_locker,
+ connector: payment_attempt.connector,
+ error_message: payment_attempt.error_message,
+ offer_amount: payment_attempt.offer_amount,
+ surcharge_amount: payment_attempt.surcharge_amount,
+ tax_amount: payment_attempt.tax_amount,
+ payment_method_id: payment_attempt.payment_method_id,
+ payment_method: payment_attempt.payment_method,
+ connector_transaction_id: None,
+ capture_method: payment_attempt.capture_method,
+ capture_on: payment_attempt.capture_on,
+ confirm: payment_attempt.confirm,
+ authentication_type: payment_attempt.authentication_type,
+ created_at: payment_attempt.created_at.unwrap_or(time),
+ modified_at: payment_attempt.modified_at.unwrap_or(time),
+ last_synced: payment_attempt.last_synced,
+ cancellation_reason: payment_attempt.cancellation_reason,
+ amount_to_capture: payment_attempt.amount_to_capture,
+ mandate_id: None,
+ browser_info: None,
+ payment_token: None,
+ error_code: payment_attempt.error_code,
+ connector_metadata: None,
+ payment_experience: payment_attempt.payment_experience,
+ payment_method_type: payment_attempt.payment_method_type,
+ payment_method_data: payment_attempt.payment_method_data,
+ business_sub_label: payment_attempt.business_sub_label,
+ straight_through_algorithm: payment_attempt.straight_through_algorithm,
+ mandate_details: payment_attempt.mandate_details,
+ preprocessing_step_id: payment_attempt.preprocessing_step_id,
+ error_reason: payment_attempt.error_reason,
+ multiple_capture_count: payment_attempt.multiple_capture_count,
+ connector_response_reference_id: None,
+ };
+ payment_attempts.push(payment_attempt.clone());
+ Ok(payment_attempt)
+ }
+
+ // safety: only used for testing
+ #[allow(clippy::unwrap_used)]
+ async fn update_payment_attempt_with_attempt_id(
+ &self,
+ this: PaymentAttempt,
+ payment_attempt: PaymentAttemptUpdate,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ let mut payment_attempts = self.payment_attempts.lock().await;
+
+ let item = payment_attempts
+ .iter_mut()
+ .find(|item| item.attempt_id == this.attempt_id)
+ .unwrap();
+
+ *item = PaymentAttempt::from_storage_model(
+ payment_attempt
+ .to_storage_model()
+ .apply_changeset(this.to_storage_model()),
+ );
+
+ Ok(item.clone())
+ }
+
+ async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
+ &self,
+ _connector_transaction_id: &str,
+ _payment_id: &str,
+ _merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ // safety: only used for testing
+ #[allow(clippy::unwrap_used)]
+ async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
+ &self,
+ payment_id: &str,
+ merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, StorageError> {
+ let payment_attempts = self.payment_attempts.lock().await;
+
+ Ok(payment_attempts
+ .iter()
+ .find(|payment_attempt| {
+ payment_attempt.payment_id == payment_id
+ && payment_attempt.merchant_id == merchant_id
+ })
+ .cloned()
+ .unwrap())
+ }
+}
diff --git a/crates/router/src/db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
similarity index 68%
rename from crates/router/src/db/payment_intent.rs
rename to crates/storage_impl/src/mock_db/payment_intent.rs
index 8a70a208de5..43d7207d452 100644
--- a/crates/router/src/db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -1,19 +1,14 @@
-use data_models::payments::payment_intent::{
- PaymentIntent, PaymentIntentInterface, PaymentIntentNew,
-};
-#[cfg(feature = "olap")]
-use data_models::payments::{
- payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
+use common_utils::errors::CustomResult;
+use data_models::{
+ errors::StorageError,
+ payments::payment_intent::{
+ PaymentIntent, PaymentIntentInterface, PaymentIntentNew, PaymentIntentUpdate,
+ },
+ MerchantStorageScheme,
};
use error_stack::{IntoReport, ResultExt};
use super::MockDb;
-#[cfg(feature = "olap")]
-use crate::types::api;
-use crate::{
- core::errors::{self, CustomResult},
- types::storage::{self as types, enums},
-};
#[async_trait::async_trait]
impl PaymentIntentInterface for MockDb {
@@ -21,58 +16,64 @@ impl PaymentIntentInterface for MockDb {
async fn filter_payment_intent_by_constraints(
&self,
_merchant_id: &str,
- _filters: &PaymentIntentFetchConstraints,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<PaymentIntent>, errors::DataStorageError> {
+ _filters: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
- Err(errors::DataStorageError::MockDbError)?
+ Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn filter_payment_intents_by_time_range_constraints(
&self,
_merchant_id: &str,
- _time_range: &api::TimeRange,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<Vec<PaymentIntent>, errors::DataStorageError> {
+ _time_range: &api_models::payments::TimeRange,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
- Err(errors::DataStorageError::MockDbError)?
+ Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
- async fn get_filtered_payment_intents_attempt(
+ async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &str,
- _constraints: &PaymentIntentFetchConstraints,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, errors::DataStorageError> {
+ _constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<Vec<String>, StorageError> {
// [#172]: Implement function for `MockDb`
- Err(errors::DataStorageError::MockDbError)?
+ Err(StorageError::MockDbError)?
}
-
#[cfg(feature = "olap")]
- async fn get_filtered_active_attempt_ids_for_total_count(
+ async fn get_filtered_payment_intents_attempt(
&self,
_merchant_id: &str,
- _constraints: &PaymentIntentFetchConstraints,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> error_stack::Result<Vec<String>, errors::DataStorageError> {
+ _constraints: &data_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<
+ Vec<(
+ PaymentIntent,
+ data_models::payments::payment_attempt::PaymentAttempt,
+ )>,
+ StorageError,
+ > {
// [#172]: Implement function for `MockDb`
- Err(errors::DataStorageError::MockDbError)?
+ Err(StorageError::MockDbError)?
}
#[allow(clippy::panic)]
async fn insert_payment_intent(
&self,
new: PaymentIntentNew,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentIntent, errors::DataStorageError> {
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let time = common_utils::date_time::now();
let payment_intent = PaymentIntent {
+ #[allow(clippy::as_conversions)]
id: payment_intents
.len()
.try_into()
.into_report()
- .change_context(errors::DataStorageError::MockDbError)?,
+ .change_context(StorageError::MockDbError)?,
payment_id: new.payment_id,
merchant_id: new.merchant_id,
status: new.status,
@@ -104,6 +105,7 @@ impl PaymentIntentInterface for MockDb {
attempt_count: new.attempt_count,
profile_id: new.profile_id,
merchant_decision: new.merchant_decision,
+ payment_confirm_source: new.payment_confirm_source,
};
payment_intents.push(payment_intent.clone());
Ok(payment_intent)
@@ -114,9 +116,9 @@ impl PaymentIntentInterface for MockDb {
async fn update_payment_intent(
&self,
this: PaymentIntent,
- update: types::PaymentIntentUpdate,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentIntent, errors::DataStorageError> {
+ update: PaymentIntentUpdate,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter_mut()
@@ -132,8 +134,8 @@ impl PaymentIntentInterface for MockDb {
&self,
payment_id: &str,
merchant_id: &str,
- _storage_scheme: enums::MerchantStorageScheme,
- ) -> CustomResult<PaymentIntent, errors::DataStorageError> {
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
Ok(payment_intents
diff --git a/crates/storage_impl/src/mock_db/redis_conn.rs b/crates/storage_impl/src/mock_db/redis_conn.rs
new file mode 100644
index 00000000000..142c7505706
--- /dev/null
+++ b/crates/storage_impl/src/mock_db/redis_conn.rs
@@ -0,0 +1,14 @@
+use std::sync::Arc;
+
+use redis_interface::errors::RedisError;
+
+use super::MockDb;
+use crate::redis::kv_store::RedisConnInterface;
+
+impl RedisConnInterface for MockDb {
+ fn get_redis_conn(
+ &self,
+ ) -> Result<Arc<redis_interface::RedisConnectionPool>, error_stack::Report<RedisError>> {
+ self.redis.get_redis_conn()
+ }
+}
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 218d87cdfa2..c2a5a97da1e 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1,13 +1,814 @@
+use api_models::enums::{Connector, PaymentMethod};
+use common_utils::errors::CustomResult;
use data_models::{
+ errors,
mandates::{MandateAmountData, MandateDataType},
- payments::payment_attempt::PaymentAttempt,
+ payments::{
+ payment_attempt::{
+ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
+ PaymentListFilters,
+ },
+ payment_intent::PaymentIntent,
+ },
+ MerchantStorageScheme,
};
use diesel_models::{
enums::{MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType},
- payment_attempt::PaymentAttempt as DieselPaymentAttempt,
+ kv,
+ payment_attempt::{
+ PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew,
+ PaymentAttemptUpdate as DieselPaymentAttemptUpdate,
+ },
+ reverse_lookup::{ReverseLookup, ReverseLookupNew},
};
+use error_stack::{IntoReport, ResultExt};
+use redis_interface::HsetnxReply;
-use crate::DataModelExt;
+use crate::{
+ lookup::ReverseLookupInterface,
+ redis::kv_store::{PartitionKey, RedisConnInterface},
+ utils::{
+ generate_hscan_pattern_for_attempt, pg_connection_read, pg_connection_write,
+ try_redis_get_else_try_database_get,
+ },
+ DataModelExt, DatabaseStore, KVRouterStore, RouterStore,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
+ async fn insert_payment_attempt(
+ &self,
+ payment_attempt: PaymentAttemptNew,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_write(self).await?;
+ payment_attempt
+ .to_storage_model()
+ .insert(&conn)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn update_payment_attempt_with_attempt_id(
+ &self,
+ this: PaymentAttempt,
+ payment_attempt: PaymentAttemptUpdate,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_write(self).await?;
+ this.to_storage_model()
+ .update_with_attempt_id(&conn, payment_attempt.to_storage_model())
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
+ &self,
+ connector_transaction_id: &str,
+ payment_id: &str,
+ merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ DieselPaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id(
+ &conn,
+ connector_transaction_id,
+ payment_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
+ &self,
+ payment_id: &str,
+ merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ DieselPaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id(
+ &conn,
+ payment_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn find_payment_attempt_by_merchant_id_connector_txn_id(
+ &self,
+ merchant_id: &str,
+ connector_txn_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ DieselPaymentAttempt::find_by_merchant_id_connector_txn_id(
+ &conn,
+ merchant_id,
+ connector_txn_id,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
+ &self,
+ payment_id: &str,
+ merchant_id: &str,
+ attempt_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+
+ DieselPaymentAttempt::find_by_payment_id_merchant_id_attempt_id(
+ &conn,
+ payment_id,
+ merchant_id,
+ attempt_id,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn get_filters_for_payments(
+ &self,
+ pi: &[PaymentIntent],
+ merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentListFilters, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ let intents = pi
+ .iter()
+ .cloned()
+ .map(|pi| pi.to_storage_model())
+ .collect::<Vec<diesel_models::payment_intent::PaymentIntent>>();
+ DieselPaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(
+ |(connector, currency, status, payment_method)| PaymentListFilters {
+ connector,
+ currency,
+ status,
+ payment_method,
+ },
+ )
+ }
+
+ async fn find_payment_attempt_by_preprocessing_id_merchant_id(
+ &self,
+ preprocessing_id: &str,
+ merchant_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+
+ DieselPaymentAttempt::find_by_merchant_id_preprocessing_id(
+ &conn,
+ merchant_id,
+ preprocessing_id,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn find_attempts_by_merchant_id_payment_id(
+ &self,
+ merchant_id: &str,
+ payment_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ DieselPaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(|a| {
+ a.into_iter()
+ .map(PaymentAttempt::from_storage_model)
+ .collect()
+ })
+ }
+
+ async fn find_payment_attempt_by_attempt_id_merchant_id(
+ &self,
+ merchant_id: &str,
+ attempt_id: &str,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+
+ DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ .map(PaymentAttempt::from_storage_model)
+ }
+
+ async fn get_total_count_of_filtered_payment_attempts(
+ &self,
+ merchant_id: &str,
+ active_attempt_ids: &[String],
+ connector: Option<Vec<Connector>>,
+ payment_methods: Option<Vec<PaymentMethod>>,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let conn = self
+ .db_store
+ .get_replica_pool()
+ .get()
+ .await
+ .into_report()
+ .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let connector_strings = connector.as_ref().map(|connector| {
+ connector
+ .iter()
+ .map(|c| c.to_string())
+ .collect::<Vec<String>>()
+ });
+ DieselPaymentAttempt::get_total_count_of_attempts(
+ &conn,
+ merchant_id,
+ active_attempt_ids,
+ connector_strings,
+ payment_methods,
+ )
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
+ async fn insert_payment_attempt(
+ &self,
+ payment_attempt: PaymentAttemptNew,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .insert_payment_attempt(payment_attempt, storage_scheme)
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let key = format!(
+ "{}_{}",
+ payment_attempt.merchant_id, payment_attempt.payment_id
+ );
+
+ let created_attempt = PaymentAttempt {
+ id: Default::default(),
+ payment_id: payment_attempt.payment_id.clone(),
+ merchant_id: payment_attempt.merchant_id.clone(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ status: payment_attempt.status,
+ amount: payment_attempt.amount,
+ currency: payment_attempt.currency,
+ save_to_locker: payment_attempt.save_to_locker,
+ connector: payment_attempt.connector.clone(),
+ error_message: payment_attempt.error_message.clone(),
+ offer_amount: payment_attempt.offer_amount,
+ surcharge_amount: payment_attempt.surcharge_amount,
+ tax_amount: payment_attempt.tax_amount,
+ payment_method_id: payment_attempt.payment_method_id.clone(),
+ payment_method: payment_attempt.payment_method,
+ connector_transaction_id: None,
+ capture_method: payment_attempt.capture_method,
+ capture_on: payment_attempt.capture_on,
+ confirm: payment_attempt.confirm,
+ authentication_type: payment_attempt.authentication_type,
+ created_at: payment_attempt
+ .created_at
+ .unwrap_or_else(common_utils::date_time::now),
+ modified_at: payment_attempt
+ .created_at
+ .unwrap_or_else(common_utils::date_time::now),
+ last_synced: payment_attempt.last_synced,
+ amount_to_capture: payment_attempt.amount_to_capture,
+ cancellation_reason: payment_attempt.cancellation_reason.clone(),
+ mandate_id: payment_attempt.mandate_id.clone(),
+ browser_info: payment_attempt.browser_info.clone(),
+ payment_token: payment_attempt.payment_token.clone(),
+ error_code: payment_attempt.error_code.clone(),
+ connector_metadata: payment_attempt.connector_metadata.clone(),
+ payment_experience: payment_attempt.payment_experience,
+ payment_method_type: payment_attempt.payment_method_type,
+ payment_method_data: payment_attempt.payment_method_data.clone(),
+ business_sub_label: payment_attempt.business_sub_label.clone(),
+ straight_through_algorithm: payment_attempt.straight_through_algorithm.clone(),
+ mandate_details: payment_attempt.mandate_details.clone(),
+ preprocessing_step_id: payment_attempt.preprocessing_step_id.clone(),
+ error_reason: payment_attempt.error_reason.clone(),
+ multiple_capture_count: payment_attempt.multiple_capture_count,
+ connector_response_reference_id: None,
+ };
+
+ let field = format!("pa_{}", created_attempt.attempt_id);
+ match self
+ .get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_attempt)
+ .await
+ {
+ Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
+ entity: "payment attempt",
+ key: Some(key),
+ })
+ .into_report(),
+ Ok(HsetnxReply::KeySet) => {
+ let conn = pg_connection_write(self).await?;
+
+ //Reverse lookup for attempt_id
+ ReverseLookupNew {
+ lookup_id: format!(
+ "{}_{}",
+ &created_attempt.merchant_id, &created_attempt.attempt_id,
+ ),
+ pk_id: key,
+ sk_id: field,
+ source: "payment_attempt".to_string(),
+ }
+ .insert(&conn)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })?;
+
+ let redis_entry = kv::TypedSql {
+ op: kv::DBOperation::Insert {
+ insertable: kv::Insertable::PaymentAttempt(
+ payment_attempt.to_storage_model(),
+ ),
+ },
+ };
+ self.push_to_drainer_stream::<DieselPaymentAttempt>(
+ redis_entry,
+ PartitionKey::MerchantIdPaymentId {
+ merchant_id: &created_attempt.merchant_id,
+ payment_id: &created_attempt.payment_id,
+ },
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ Ok(created_attempt)
+ }
+ Err(error) => Err(error.change_context(errors::StorageError::KVError)),
+ }
+ }
+ }
+ }
+
+ async fn update_payment_attempt_with_attempt_id(
+ &self,
+ this: PaymentAttempt,
+ payment_attempt: PaymentAttemptUpdate,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .update_payment_attempt_with_attempt_id(this, payment_attempt, storage_scheme)
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let key = format!("{}_{}", this.merchant_id, this.payment_id);
+ let old_connector_transaction_id = &this.connector_transaction_id;
+ let old_preprocessing_id = &this.preprocessing_step_id;
+ let updated_attempt = PaymentAttempt::from_storage_model(
+ payment_attempt
+ .clone()
+ .to_storage_model()
+ .apply_changeset(this.clone().to_storage_model()),
+ );
+ // Check for database presence as well Maybe use a read replica here ?
+ let redis_value = serde_json::to_string(&updated_attempt)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+ let field = format!("pa_{}", updated_attempt.attempt_id);
+ let updated_attempt = self
+ .get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .set_hash_fields(&key, (&field, &redis_value))
+ .await
+ .map(|_| updated_attempt)
+ .change_context(errors::StorageError::KVError)?;
+
+ match (
+ old_connector_transaction_id,
+ &updated_attempt.connector_transaction_id,
+ ) {
+ (None, Some(connector_transaction_id)) => {
+ add_connector_txn_id_to_reverse_lookup(
+ &self.router_store,
+ key.as_str(),
+ this.merchant_id.as_str(),
+ updated_attempt.attempt_id.as_str(),
+ connector_transaction_id.as_str(),
+ )
+ .await?;
+ }
+ (Some(old_connector_transaction_id), Some(connector_transaction_id)) => {
+ if old_connector_transaction_id.ne(connector_transaction_id) {
+ add_connector_txn_id_to_reverse_lookup(
+ &self.router_store,
+ key.as_str(),
+ this.merchant_id.as_str(),
+ updated_attempt.attempt_id.as_str(),
+ connector_transaction_id.as_str(),
+ )
+ .await?;
+ }
+ }
+ (_, _) => {}
+ }
+
+ match (old_preprocessing_id, &updated_attempt.preprocessing_step_id) {
+ (None, Some(preprocessing_id)) => {
+ add_preprocessing_id_to_reverse_lookup(
+ &self.router_store,
+ key.as_str(),
+ this.merchant_id.as_str(),
+ updated_attempt.attempt_id.as_str(),
+ preprocessing_id.as_str(),
+ )
+ .await?;
+ }
+ (Some(old_preprocessing_id), Some(preprocessing_id)) => {
+ if old_preprocessing_id.ne(preprocessing_id) {
+ add_preprocessing_id_to_reverse_lookup(
+ &self.router_store,
+ key.as_str(),
+ this.merchant_id.as_str(),
+ updated_attempt.attempt_id.as_str(),
+ preprocessing_id.as_str(),
+ )
+ .await?;
+ }
+ }
+ (_, _) => {}
+ }
+
+ let redis_entry = kv::TypedSql {
+ op: kv::DBOperation::Update {
+ updatable: kv::Updateable::PaymentAttemptUpdate(
+ kv::PaymentAttemptUpdateMems {
+ orig: this.to_storage_model(),
+ update_data: payment_attempt.to_storage_model(),
+ },
+ ),
+ },
+ };
+ self.push_to_drainer_stream::<DieselPaymentAttempt>(
+ redis_entry,
+ PartitionKey::MerchantIdPaymentId {
+ merchant_id: &updated_attempt.merchant_id,
+ payment_id: &updated_attempt.payment_id,
+ },
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ Ok(updated_attempt)
+ }
+ }
+ }
+
+ async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
+ &self,
+ connector_transaction_id: &str,
+ payment_id: &str,
+ merchant_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
+ connector_transaction_id,
+ payment_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ // We assume that PaymentAttempt <=> PaymentIntent is a one-to-one relation for now
+ let lookup_id = format!("{merchant_id}_{connector_transaction_id}");
+ let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
+ let key = &lookup.pk_id;
+
+ try_redis_get_else_try_database_get(
+ self.get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
+ || async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme).await},
+ )
+ .await
+ }
+ }
+ }
+
+ async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
+ &self,
+ payment_id: &str,
+ merchant_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ self.router_store
+ .find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
+ payment_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ }
+
+ async fn find_payment_attempt_by_merchant_id_connector_txn_id(
+ &self,
+ merchant_id: &str,
+ connector_txn_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .find_payment_attempt_by_merchant_id_connector_txn_id(
+ merchant_id,
+ connector_txn_id,
+ storage_scheme,
+ )
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("{merchant_id}_{connector_txn_id}");
+ let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
+
+ let key = &lookup.pk_id;
+ try_redis_get_else_try_database_get(
+ self.get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
+ || async {
+ self.router_store
+ .find_payment_attempt_by_merchant_id_connector_txn_id(
+ merchant_id,
+ connector_txn_id,
+ storage_scheme,
+ )
+ .await
+ },
+ )
+ .await
+ }
+ }
+ }
+
+ async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
+ &self,
+ payment_id: &str,
+ merchant_id: &str,
+ attempt_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .find_payment_attempt_by_payment_id_merchant_id_attempt_id(
+ payment_id,
+ merchant_id,
+ attempt_id,
+ storage_scheme,
+ )
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("{merchant_id}_{attempt_id}");
+ let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
+ let key = &lookup.pk_id;
+ try_redis_get_else_try_database_get(
+ self.get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
+ || async {
+ self.router_store
+ .find_payment_attempt_by_payment_id_merchant_id_attempt_id(
+ payment_id,
+ merchant_id,
+ attempt_id,
+ storage_scheme,
+ )
+ .await
+ },
+ )
+ .await
+ }
+ }
+ }
+
+ async fn find_payment_attempt_by_attempt_id_merchant_id(
+ &self,
+ attempt_id: &str,
+ merchant_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .find_payment_attempt_by_attempt_id_merchant_id(
+ attempt_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("{merchant_id}_{attempt_id}");
+ let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
+ let key = &lookup.pk_id;
+ try_redis_get_else_try_database_get(
+ self.get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
+ || async {
+ self.router_store
+ .find_payment_attempt_by_attempt_id_merchant_id(
+ attempt_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ },
+ )
+ .await
+ }
+ }
+ }
+
+ async fn find_payment_attempt_by_preprocessing_id_merchant_id(
+ &self,
+ preprocessing_id: &str,
+ merchant_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .find_payment_attempt_by_preprocessing_id_merchant_id(
+ preprocessing_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let lookup_id = format!("{merchant_id}_{preprocessing_id}");
+ let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?;
+ let key = &lookup.pk_id;
+
+ try_redis_get_else_try_database_get(
+ self.get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"),
+ || async {
+ self.router_store
+ .find_payment_attempt_by_preprocessing_id_merchant_id(
+ preprocessing_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ },
+ )
+ .await
+ }
+ }
+ }
+
+ async fn find_attempts_by_merchant_id_payment_id(
+ &self,
+ merchant_id: &str,
+ payment_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ self.router_store
+ .find_attempts_by_merchant_id_payment_id(
+ merchant_id,
+ payment_id,
+ storage_scheme,
+ )
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let key = format!("{merchant_id}_{payment_id}");
+ let lookup = self.get_lookup_by_lookup_id(&key).await?;
+
+ let pattern = generate_hscan_pattern_for_attempt(&lookup.sk_id);
+
+ self.get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(errors::StorageError::RedisError(error))
+ })?
+ .hscan_and_deserialize(&key, &pattern, None)
+ .await
+ .change_context(errors::StorageError::KVError)
+ }
+ }
+ }
+
+ async fn get_filters_for_payments(
+ &self,
+ pi: &[PaymentIntent],
+ merchant_id: &str,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<PaymentListFilters, errors::StorageError> {
+ self.router_store
+ .get_filters_for_payments(pi, merchant_id, storage_scheme)
+ .await
+ }
+
+ async fn get_total_count_of_filtered_payment_attempts(
+ &self,
+ merchant_id: &str,
+ active_attempt_ids: &[String],
+ connector: Option<Vec<Connector>>,
+ payment_methods: Option<Vec<PaymentMethod>>,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<i64, errors::StorageError> {
+ self.router_store
+ .get_total_count_of_filtered_payment_attempts(
+ merchant_id,
+ active_attempt_ids,
+ connector,
+ payment_methods,
+ storage_scheme,
+ )
+ .await
+ }
+}
impl DataModelExt for MandateAmountData {
type StorageModel = DieselMandateAmountData;
@@ -154,3 +955,497 @@ impl DataModelExt for PaymentAttempt {
}
}
}
+
+impl DataModelExt for PaymentAttemptNew {
+ type StorageModel = DieselPaymentAttemptNew;
+
+ fn to_storage_model(self) -> Self::StorageModel {
+ DieselPaymentAttemptNew {
+ payment_id: self.payment_id,
+ merchant_id: self.merchant_id,
+ attempt_id: self.attempt_id,
+ status: self.status,
+ amount: self.amount,
+ currency: self.currency,
+ save_to_locker: self.save_to_locker,
+ connector: self.connector,
+ error_message: self.error_message,
+ offer_amount: self.offer_amount,
+ surcharge_amount: self.surcharge_amount,
+ tax_amount: self.tax_amount,
+ payment_method_id: self.payment_method_id,
+ payment_method: self.payment_method,
+ capture_method: self.capture_method,
+ capture_on: self.capture_on,
+ confirm: self.confirm,
+ authentication_type: self.authentication_type,
+ created_at: self.created_at,
+ modified_at: self.modified_at,
+ last_synced: self.last_synced,
+ cancellation_reason: self.cancellation_reason,
+ amount_to_capture: self.amount_to_capture,
+ mandate_id: self.mandate_id,
+ browser_info: self.browser_info,
+ payment_token: self.payment_token,
+ error_code: self.error_code,
+ connector_metadata: self.connector_metadata,
+ payment_experience: self.payment_experience,
+ payment_method_type: self.payment_method_type,
+ payment_method_data: self.payment_method_data,
+ business_sub_label: self.business_sub_label,
+ straight_through_algorithm: self.straight_through_algorithm,
+ preprocessing_step_id: self.preprocessing_step_id,
+ mandate_details: self.mandate_details.map(|d| d.to_storage_model()),
+ error_reason: self.error_reason,
+ connector_response_reference_id: self.connector_response_reference_id,
+ multiple_capture_count: self.multiple_capture_count,
+ }
+ }
+
+ fn from_storage_model(storage_model: Self::StorageModel) -> Self {
+ Self {
+ payment_id: storage_model.payment_id,
+ merchant_id: storage_model.merchant_id,
+ attempt_id: storage_model.attempt_id,
+ status: storage_model.status,
+ amount: storage_model.amount,
+ currency: storage_model.currency,
+ save_to_locker: storage_model.save_to_locker,
+ connector: storage_model.connector,
+ error_message: storage_model.error_message,
+ offer_amount: storage_model.offer_amount,
+ surcharge_amount: storage_model.surcharge_amount,
+ tax_amount: storage_model.tax_amount,
+ payment_method_id: storage_model.payment_method_id,
+ payment_method: storage_model.payment_method,
+ capture_method: storage_model.capture_method,
+ capture_on: storage_model.capture_on,
+ confirm: storage_model.confirm,
+ authentication_type: storage_model.authentication_type,
+ created_at: storage_model.created_at,
+ modified_at: storage_model.modified_at,
+ last_synced: storage_model.last_synced,
+ cancellation_reason: storage_model.cancellation_reason,
+ amount_to_capture: storage_model.amount_to_capture,
+ mandate_id: storage_model.mandate_id,
+ browser_info: storage_model.browser_info,
+ payment_token: storage_model.payment_token,
+ error_code: storage_model.error_code,
+ connector_metadata: storage_model.connector_metadata,
+ payment_experience: storage_model.payment_experience,
+ payment_method_type: storage_model.payment_method_type,
+ payment_method_data: storage_model.payment_method_data,
+ business_sub_label: storage_model.business_sub_label,
+ straight_through_algorithm: storage_model.straight_through_algorithm,
+ preprocessing_step_id: storage_model.preprocessing_step_id,
+ mandate_details: storage_model
+ .mandate_details
+ .map(MandateDataType::from_storage_model),
+ error_reason: storage_model.error_reason,
+ connector_response_reference_id: storage_model.connector_response_reference_id,
+ multiple_capture_count: storage_model.multiple_capture_count,
+ }
+ }
+}
+
+impl DataModelExt for PaymentAttemptUpdate {
+ type StorageModel = DieselPaymentAttemptUpdate;
+
+ fn to_storage_model(self) -> Self::StorageModel {
+ match self {
+ Self::Update {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ amount_to_capture,
+ capture_method,
+ } => DieselPaymentAttemptUpdate::Update {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ amount_to_capture,
+ capture_method,
+ },
+ Self::UpdateTrackers {
+ payment_token,
+ connector,
+ straight_through_algorithm,
+ } => DieselPaymentAttemptUpdate::UpdateTrackers {
+ payment_token,
+ connector,
+ straight_through_algorithm,
+ },
+ Self::AuthenticationTypeUpdate {
+ authentication_type,
+ } => DieselPaymentAttemptUpdate::AuthenticationTypeUpdate {
+ authentication_type,
+ },
+ Self::ConfirmUpdate {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ browser_info,
+ connector,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ straight_through_algorithm,
+ error_code,
+ error_message,
+ } => DieselPaymentAttemptUpdate::ConfirmUpdate {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ browser_info,
+ connector,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ straight_through_algorithm,
+ error_code,
+ error_message,
+ },
+ Self::VoidUpdate {
+ status,
+ cancellation_reason,
+ } => DieselPaymentAttemptUpdate::VoidUpdate {
+ status,
+ cancellation_reason,
+ },
+ Self::ResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ authentication_type,
+ payment_method_id,
+ mandate_id,
+ connector_metadata,
+ payment_token,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ } => DieselPaymentAttemptUpdate::ResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ authentication_type,
+ payment_method_id,
+ mandate_id,
+ connector_metadata,
+ payment_token,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ },
+ Self::UnresolvedResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ payment_method_id,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ } => DieselPaymentAttemptUpdate::UnresolvedResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ payment_method_id,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ },
+ Self::StatusUpdate { status } => DieselPaymentAttemptUpdate::StatusUpdate { status },
+ Self::ErrorUpdate {
+ connector,
+ status,
+ error_code,
+ error_message,
+ error_reason,
+ } => DieselPaymentAttemptUpdate::ErrorUpdate {
+ connector,
+ status,
+ error_code,
+ error_message,
+ error_reason,
+ },
+ Self::MultipleCaptureCountUpdate {
+ multiple_capture_count,
+ } => DieselPaymentAttemptUpdate::MultipleCaptureCountUpdate {
+ multiple_capture_count,
+ },
+ Self::PreprocessingUpdate {
+ status,
+ payment_method_id,
+ connector_metadata,
+ preprocessing_step_id,
+ connector_transaction_id,
+ connector_response_reference_id,
+ } => DieselPaymentAttemptUpdate::PreprocessingUpdate {
+ status,
+ payment_method_id,
+ connector_metadata,
+ preprocessing_step_id,
+ connector_transaction_id,
+ connector_response_reference_id,
+ },
+ Self::RejectUpdate {
+ status,
+ error_code,
+ error_message,
+ } => DieselPaymentAttemptUpdate::RejectUpdate {
+ status,
+ error_code,
+ error_message,
+ },
+ }
+ }
+
+ fn from_storage_model(storage_model: Self::StorageModel) -> Self {
+ match storage_model {
+ DieselPaymentAttemptUpdate::Update {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ amount_to_capture,
+ capture_method,
+ } => Self::Update {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ amount_to_capture,
+ capture_method,
+ },
+ DieselPaymentAttemptUpdate::UpdateTrackers {
+ payment_token,
+ connector,
+ straight_through_algorithm,
+ } => Self::UpdateTrackers {
+ payment_token,
+ connector,
+ straight_through_algorithm,
+ },
+ DieselPaymentAttemptUpdate::AuthenticationTypeUpdate {
+ authentication_type,
+ } => Self::AuthenticationTypeUpdate {
+ authentication_type,
+ },
+ DieselPaymentAttemptUpdate::ConfirmUpdate {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ browser_info,
+ connector,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ straight_through_algorithm,
+ error_code,
+ error_message,
+ } => Self::ConfirmUpdate {
+ amount,
+ currency,
+ status,
+ authentication_type,
+ payment_method,
+ browser_info,
+ connector,
+ payment_token,
+ payment_method_data,
+ payment_method_type,
+ payment_experience,
+ business_sub_label,
+ straight_through_algorithm,
+ error_code,
+ error_message,
+ },
+ DieselPaymentAttemptUpdate::VoidUpdate {
+ status,
+ cancellation_reason,
+ } => Self::VoidUpdate {
+ status,
+ cancellation_reason,
+ },
+ DieselPaymentAttemptUpdate::ResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ authentication_type,
+ payment_method_id,
+ mandate_id,
+ connector_metadata,
+ payment_token,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ } => Self::ResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ authentication_type,
+ payment_method_id,
+ mandate_id,
+ connector_metadata,
+ payment_token,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ },
+ DieselPaymentAttemptUpdate::UnresolvedResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ payment_method_id,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ } => Self::UnresolvedResponseUpdate {
+ status,
+ connector,
+ connector_transaction_id,
+ payment_method_id,
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ },
+ DieselPaymentAttemptUpdate::StatusUpdate { status } => Self::StatusUpdate { status },
+ DieselPaymentAttemptUpdate::ErrorUpdate {
+ connector,
+ status,
+ error_code,
+ error_message,
+ error_reason,
+ } => Self::ErrorUpdate {
+ connector,
+ status,
+ error_code,
+ error_message,
+ error_reason,
+ },
+ DieselPaymentAttemptUpdate::MultipleCaptureCountUpdate {
+ multiple_capture_count,
+ } => Self::MultipleCaptureCountUpdate {
+ multiple_capture_count,
+ },
+ DieselPaymentAttemptUpdate::PreprocessingUpdate {
+ status,
+ payment_method_id,
+ connector_metadata,
+ preprocessing_step_id,
+ connector_transaction_id,
+ connector_response_reference_id,
+ } => Self::PreprocessingUpdate {
+ status,
+ payment_method_id,
+ connector_metadata,
+ preprocessing_step_id,
+ connector_transaction_id,
+ connector_response_reference_id,
+ },
+ DieselPaymentAttemptUpdate::RejectUpdate {
+ status,
+ error_code,
+ error_message,
+ } => Self::RejectUpdate {
+ status,
+ error_code,
+ error_message,
+ },
+ }
+ }
+}
+
+#[inline]
+async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>(
+ store: &RouterStore<T>,
+ key: &str,
+ merchant_id: &str,
+ updated_attempt_attempt_id: &str,
+ connector_transaction_id: &str,
+) -> CustomResult<ReverseLookup, errors::StorageError> {
+ let conn = pg_connection_write(store).await?;
+ let field = format!("pa_{}", updated_attempt_attempt_id);
+ ReverseLookupNew {
+ lookup_id: format!("{}_{}", merchant_id, connector_transaction_id),
+ pk_id: key.to_owned(),
+ sk_id: field.clone(),
+ source: "payment_attempt".to_string(),
+ }
+ .insert(&conn)
+ .await
+ .map_err(|err| {
+ let new_err = crate::diesel_error_to_data_error(err.current_context());
+ err.change_context(new_err)
+ })
+}
+
+#[inline]
+async fn add_preprocessing_id_to_reverse_lookup<T: DatabaseStore>(
+ store: &RouterStore<T>,
+ key: &str,
+ merchant_id: &str,
+ updated_attempt_attempt_id: &str,
+ preprocessing_id: &str,
+) -> CustomResult<ReverseLookup, errors::StorageError> {
+ let conn = pg_connection_write(store).await?;
+ let field = format!("pa_{}", updated_attempt_attempt_id);
+ ReverseLookupNew {
+ lookup_id: format!("{}_{}", merchant_id, preprocessing_id),
+ pk_id: key.to_owned(),
+ sk_id: field.clone(),
+ source: "payment_attempt".to_string(),
+ }
+ .insert(&conn)
+ .await
+ .map_err(|er| {
+ let new_err = crate::diesel_error_to_data_error(er.current_context());
+ er.change_context(new_err)
+ })
+}
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 8f20746ec03..eaac73cb6c7 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -36,7 +36,7 @@ use router_env::logger;
use crate::{
redis::kv_store::{PartitionKey, RedisConnInterface},
utils::{pg_connection_read, pg_connection_write},
- CustomResult, DataModelExt, DatabaseStore, KVRouterStore, MockDb,
+ DataModelExt, DatabaseStore, KVRouterStore,
};
#[async_trait::async_trait]
@@ -663,138 +663,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
}
}
-#[async_trait::async_trait]
-impl PaymentIntentInterface for MockDb {
- #[cfg(feature = "olap")]
- async fn filter_payment_intent_by_constraints(
- &self,
- _merchant_id: &str,
- _filters: &PaymentIntentFetchConstraints,
- _storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<PaymentIntent>, StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(StorageError::MockDbError)?
- }
- #[cfg(feature = "olap")]
- async fn filter_payment_intents_by_time_range_constraints(
- &self,
- _merchant_id: &str,
- _time_range: &api_models::payments::TimeRange,
- _storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Vec<PaymentIntent>, StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(StorageError::MockDbError)?
- }
- #[cfg(feature = "olap")]
- async fn get_filtered_active_attempt_ids_for_total_count(
- &self,
- _merchant_id: &str,
- _constraints: &PaymentIntentFetchConstraints,
- _storage_scheme: MerchantStorageScheme,
- ) -> error_stack::Result<Vec<String>, StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(StorageError::MockDbError)?
- }
- #[cfg(feature = "olap")]
- async fn get_filtered_payment_intents_attempt(
- &self,
- _merchant_id: &str,
- _constraints: &PaymentIntentFetchConstraints,
- _storage_scheme: MerchantStorageScheme,
- ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(StorageError::MockDbError)?
- }
-
- #[allow(clippy::panic)]
- async fn insert_payment_intent(
- &self,
- new: PaymentIntentNew,
- _storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<PaymentIntent, StorageError> {
- let mut payment_intents = self.payment_intents.lock().await;
- let time = common_utils::date_time::now();
- let payment_intent = PaymentIntent {
- #[allow(clippy::as_conversions)]
- id: payment_intents
- .len()
- .try_into()
- .into_report()
- .change_context(StorageError::MockDbError)?,
- payment_id: new.payment_id,
- merchant_id: new.merchant_id,
- status: new.status,
- amount: new.amount,
- currency: new.currency,
- amount_captured: new.amount_captured,
- customer_id: new.customer_id,
- description: new.description,
- return_url: new.return_url,
- metadata: new.metadata,
- connector_id: new.connector_id,
- shipping_address_id: new.shipping_address_id,
- billing_address_id: new.billing_address_id,
- statement_descriptor_name: new.statement_descriptor_name,
- statement_descriptor_suffix: new.statement_descriptor_suffix,
- created_at: new.created_at.unwrap_or(time),
- modified_at: new.modified_at.unwrap_or(time),
- last_synced: new.last_synced,
- setup_future_usage: new.setup_future_usage,
- off_session: new.off_session,
- client_secret: new.client_secret,
- business_country: new.business_country,
- business_label: new.business_label,
- active_attempt_id: new.active_attempt_id.to_owned(),
- order_details: new.order_details,
- allowed_payment_method_types: new.allowed_payment_method_types,
- connector_metadata: new.connector_metadata,
- feature_metadata: new.feature_metadata,
- attempt_count: new.attempt_count,
- profile_id: new.profile_id,
- merchant_decision: new.merchant_decision,
- payment_confirm_source: new.payment_confirm_source,
- };
- payment_intents.push(payment_intent.clone());
- Ok(payment_intent)
- }
-
- // safety: only used for testing
- #[allow(clippy::unwrap_used)]
- async fn update_payment_intent(
- &self,
- this: PaymentIntent,
- update: PaymentIntentUpdate,
- _storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<PaymentIntent, StorageError> {
- let mut payment_intents = self.payment_intents.lock().await;
- let payment_intent = payment_intents
- .iter_mut()
- .find(|item| item.id == this.id)
- .unwrap();
- *payment_intent = update.apply_changeset(this);
- Ok(payment_intent.clone())
- }
-
- // safety: only used for testing
- #[allow(clippy::unwrap_used)]
- async fn find_payment_intent_by_payment_id_merchant_id(
- &self,
- payment_id: &str,
- merchant_id: &str,
- _storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<PaymentIntent, StorageError> {
- let payment_intents = self.payment_intents.lock().await;
-
- Ok(payment_intents
- .iter()
- .find(|payment_intent| {
- payment_intent.payment_id == payment_id && payment_intent.merchant_id == merchant_id
- })
- .cloned()
- .unwrap())
- }
-}
-
impl DataModelExt for PaymentIntentNew {
type StorageModel = DieselPaymentIntentNew;
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 7d4edaca134..86974826825 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -1,11 +1,19 @@
use std::{any::Any, borrow::Cow, sync::Arc};
-use common_utils::errors;
+use common_utils::{
+ errors::{self, CustomResult},
+ ext_traits::AsyncExt,
+};
+use data_models::errors::StorageError;
use dyn_clone::DynClone;
-use error_stack::Report;
+use error_stack::{Report, ResultExt};
use moka::future::Cache as MokaCache;
use once_cell::sync::Lazy;
-use redis_interface::RedisValue;
+use redis_interface::{errors::RedisError, RedisValue};
+
+use super::{kv_store::RedisConnInterface, pub_sub::PubSubInterface};
+
+pub(crate) const PUB_SUB_CHANNEL: &str = "hyperswitch_invalidate";
/// Prefix for config cache key
const CONFIG_CACHE_PREFIX: &str = "config";
@@ -128,6 +136,127 @@ impl Cache {
}
}
+pub async fn get_or_populate_redis<T, F, Fut>(
+ store: &(dyn RedisConnInterface + Send + Sync),
+ key: &str,
+ fun: F,
+) -> CustomResult<T, StorageError>
+where
+ T: serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug,
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+{
+ let type_name = std::any::type_name::<T>();
+ let redis = &store
+ .get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(StorageError::RedisError(error))
+ })
+ .attach_printable("Failed to get redis connection")?;
+ let redis_val = redis.get_and_deserialize_key::<T>(key, type_name).await;
+ let get_data_set_redis = || async {
+ let data = fun().await?;
+ redis
+ .serialize_and_set_key(key, &data)
+ .await
+ .change_context(StorageError::KVError)?;
+ Ok::<_, Report<StorageError>>(data)
+ };
+ match redis_val {
+ Err(err) => match err.current_context() {
+ RedisError::NotFound | RedisError::JsonDeserializationFailed => {
+ get_data_set_redis().await
+ }
+ _ => Err(err
+ .change_context(StorageError::KVError)
+ .attach_printable(format!("Error while fetching cache for {type_name}"))),
+ },
+ Ok(val) => Ok(val),
+ }
+}
+
+pub async fn get_or_populate_in_memory<T, F, Fut>(
+ store: &(dyn RedisConnInterface + Send + Sync),
+ key: &str,
+ fun: F,
+ cache: &Cache,
+) -> CustomResult<T, StorageError>
+where
+ T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone,
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+{
+ let cache_val = cache.get_val::<T>(key);
+ if let Some(val) = cache_val {
+ Ok(val)
+ } else {
+ let val = get_or_populate_redis(store, key, fun).await?;
+ cache.push(key.to_string(), val.clone()).await;
+ Ok(val)
+ }
+}
+
+pub async fn redact_cache<T, F, Fut>(
+ store: &dyn RedisConnInterface,
+ key: &str,
+ fun: F,
+ in_memory: Option<&Cache>,
+) -> CustomResult<T, StorageError>
+where
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+{
+ let data = fun().await?;
+ in_memory.async_map(|cache| cache.invalidate(key)).await;
+
+ let redis_conn = store
+ .get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(StorageError::RedisError(error))
+ })
+ .attach_printable("Failed to get redis connection")?;
+
+ redis_conn
+ .delete_key(key)
+ .await
+ .change_context(StorageError::KVError)?;
+ Ok(data)
+}
+
+pub async fn publish_into_redact_channel<'a>(
+ store: &dyn RedisConnInterface,
+ key: CacheKind<'a>,
+) -> CustomResult<usize, StorageError> {
+ let redis_conn = store
+ .get_redis_conn()
+ .map_err(|er| {
+ let error = format!("{}", er);
+ er.change_context(StorageError::RedisError(error))
+ })
+ .attach_printable("Failed to get redis connection")?;
+
+ redis_conn
+ .publish(PUB_SUB_CHANNEL, key)
+ .await
+ .change_context(StorageError::KVError)
+}
+
+pub async fn publish_and_redact<'a, T, F, Fut>(
+ store: &dyn RedisConnInterface,
+ key: CacheKind<'a>,
+ fun: F,
+) -> CustomResult<T, StorageError>
+where
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+{
+ let data = fun().await?;
+ publish_into_redact_channel(store, key).await?;
+ Ok(data)
+}
+
#[cfg(test)]
mod cache_tests {
use super::*;
diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rs
index 6d6e1cd5402..92fd11debe8 100644
--- a/crates/storage_impl/src/utils.rs
+++ b/crates/storage_impl/src/utils.rs
@@ -68,3 +68,13 @@ where
},
}
}
+
+/// Generates hscan field pattern. Suppose the field is pa_1234 it will generate
+/// pa_*
+pub fn generate_hscan_pattern_for_attempt(sk: &str) -> String {
+ sk.split('_')
+ .take(1)
+ .chain(["*"])
+ .collect::<Vec<&str>>()
+ .join("_")
+}
|
refactor
|
split payment attempt models to domain + diesel (#2010)
|
67a3e8f534aa98a7331cb20a3877579efed6a348
|
2023-09-26 16:01:57
|
Sangamesh Kulkarni
|
fix: [stripe] Add customer balance in StripePaymentMethodDetailsResponse (#2369)
| false
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 962bfe52f09..ce434aa8ba1 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2181,6 +2181,7 @@ pub enum StripePaymentMethodDetailsResponse {
#[serde(rename = "wechat_pay")]
Wechatpay,
Alipay,
+ CustomerBalance,
}
#[derive(Deserialize)]
|
fix
|
[stripe] Add customer balance in StripePaymentMethodDetailsResponse (#2369)
|
891683e060d1fdda32405cfd06d737b2416acdcc
|
2023-04-21 02:52:57
|
Pa1NarK
|
fix(connector-template): Address unused import and mismatched types in connector-template (#910)
| false
|
diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index 80330a97429..75f2f02c027 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -1,7 +1,6 @@
mod transformers;
use std::fmt::Debug;
-use common_utils::errors::ReportSwitchExt;
use error_stack::{ResultExt, IntoReport};
use crate::{
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs
index 985c68a99c0..7e3caf100e1 100644
--- a/connector-template/transformers.rs
+++ b/connector-template/transformers.rs
@@ -30,7 +30,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
- complete: item.request.is_auto_capture(),
+ complete: item.request.is_auto_capture()?,
};
Ok(Self {
amount: item.request.amount,
|
fix
|
Address unused import and mismatched types in connector-template (#910)
|
2d17dad25d0966fc95f17e0ee91598ea445d4dc9
|
2025-03-17 14:37:27
|
Aniket Burman
|
feat(connector): Recurly incoming webhook support (#7439)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index d978d691074..b90bfa8aabf 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -259,7 +259,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://sandbox.juspay.in/"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago"
riskified.base_url = "https://sandbox.riskified.com/api"
shift4.base_url = "https://api.shift4.com/"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 2a2140029c8..39d6f8037a2 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -104,7 +104,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://sandbox.juspay.in/"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago"
shift4.base_url = "https://api.shift4.com/"
signifyd.base_url = "https://api.signifyd.com/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index de271d7d09e..e2ffbcd3d0c 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -108,7 +108,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://api.juspay.in"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis.redsys.es:25443/sis/realizarPago"
riskified.base_url = "https://wh.riskified.com/api/"
shift4.base_url = "https://api.shift4.com/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 64ace047dad..a6e0088876c 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -108,7 +108,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://sandbox.juspay.in/"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago"
riskified.base_url = "https://sandbox.riskified.com/api"
shift4.base_url = "https://api.shift4.com/"
diff --git a/config/development.toml b/config/development.toml
index 7c49f0b8b23..739366b6042 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -333,7 +333,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://sandbox.juspay.in/"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago"
riskified.base_url = "https://sandbox.riskified.com/api"
shift4.base_url = "https://api.shift4.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index b2f959439a6..956f7fa46d4 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -191,7 +191,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://sandbox.juspay.in/"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago"
riskified.base_url = "https://sandbox.riskified.com/api"
shift4.base_url = "https://api.shift4.com/"
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index 42bfe842138..cc86e6897f8 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -117,7 +117,7 @@ pub enum RoutableConnectors {
Prophetpay,
Rapyd,
Razorpay,
- // Recurly,
+ Recurly,
// Redsys,
Riskified,
Shift4,
@@ -263,7 +263,7 @@ pub enum Connector {
Prophetpay,
Rapyd,
Razorpay,
- //Recurly,
+ Recurly,
// Redsys,
Shift4,
Square,
@@ -415,7 +415,7 @@ impl Connector {
| Self::Powertranz
| Self::Prophetpay
| Self::Rapyd
- // | Self::Recurly
+ | Self::Recurly
// | Self::Redsys
| Self::Shift4
| Self::Square
@@ -552,7 +552,7 @@ impl From<RoutableConnectors> for Connector {
RoutableConnectors::Prophetpay => Self::Prophetpay,
RoutableConnectors::Rapyd => Self::Rapyd,
RoutableConnectors::Razorpay => Self::Razorpay,
- // RoutableConnectors::Recurly => Self::Recurly,
+ RoutableConnectors::Recurly => Self::Recurly,
RoutableConnectors::Riskified => Self::Riskified,
RoutableConnectors::Shift4 => Self::Shift4,
RoutableConnectors::Signifyd => Self::Signifyd,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 7cda81e7669..baa9dd13198 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -230,6 +230,7 @@ pub struct ConnectorConfig {
pub powertranz: Option<ConnectorTomlConfig>,
pub prophetpay: Option<ConnectorTomlConfig>,
pub razorpay: Option<ConnectorTomlConfig>,
+ pub recurly: Option<ConnectorTomlConfig>,
pub riskified: Option<ConnectorTomlConfig>,
pub rapyd: Option<ConnectorTomlConfig>,
pub shift4: Option<ConnectorTomlConfig>,
@@ -400,6 +401,7 @@ impl ConnectorConfig {
Connector::Powertranz => Ok(connector_data.powertranz),
Connector::Razorpay => Ok(connector_data.razorpay),
Connector::Rapyd => Ok(connector_data.rapyd),
+ Connector::Recurly => Ok(connector_data.recurly),
Connector::Riskified => Ok(connector_data.riskified),
Connector::Shift4 => Ok(connector_data.shift4),
Connector::Signifyd => Ok(connector_data.signifyd),
diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs
index c16810a6ab7..edf5141a11d 100644
--- a/crates/hyperswitch_connectors/src/connectors/recurly.rs
+++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs
@@ -1,5 +1,4 @@
pub mod transformers;
-
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
@@ -39,7 +38,10 @@ use hyperswitch_interfaces::{
use masking::{ExposeInterface, Mask};
use transformers as recurly;
-use crate::{constants::headers, types::ResponseRouterData, utils};
+use crate::{
+ connectors::recurly::transformers::RecurlyWebhookBody, constants::headers,
+ types::ResponseRouterData, utils,
+};
#[derive(Clone)]
pub struct Recurly {
@@ -52,6 +54,23 @@ impl Recurly {
amount_converter: &StringMinorUnitForConnector,
}
}
+
+ fn get_signature_elements_from_header(
+ headers: &actix_web::http::header::HeaderMap,
+ ) -> CustomResult<Vec<Vec<u8>>, errors::ConnectorError> {
+ let security_header = headers
+ .get("recurly-signature")
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
+ let security_header_str = security_header
+ .to_str()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
+ let header_parts: Vec<Vec<u8>> = security_header_str
+ .split(',')
+ .map(|part| part.trim().as_bytes().to_vec())
+ .collect();
+
+ Ok(header_parts)
+ }
}
impl api::Payment for Recurly {}
@@ -543,6 +562,58 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Recurly {
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Recurly {
+ fn get_webhook_source_verification_algorithm(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError>
+ {
+ Ok(Box::new(common_utils::crypto::HmacSha256))
+ }
+
+ fn get_webhook_source_verification_signature(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ // The `recurly-signature` header consists of a Unix timestamp (in milliseconds) followed by one or more HMAC-SHA256 signatures, separated by commas.
+ // Multiple signatures exist when a secret key is regenerated, with the old key remaining active for 24 hours.
+ let header_values = Self::get_signature_elements_from_header(request.headers)?;
+ let signature = header_values
+ .get(1)
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
+ hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
+ }
+
+ fn get_webhook_source_verification_message(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let header_values = Self::get_signature_elements_from_header(request.headers)?;
+ let timestamp = header_values
+ .first()
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
+ Ok(format!(
+ "{}.{}",
+ String::from_utf8_lossy(timestamp),
+ String::from_utf8_lossy(request.body)
+ )
+ .into_bytes())
+ }
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ let webhook = RecurlyWebhookBody::get_webhook_object_from_body(request.body)
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(webhook.uuid),
+ ))
+ }
+
+ #[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))]
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
@@ -550,6 +621,25 @@ impl webhooks::IncomingWebhook for Recurly {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
+ #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
+ fn get_webhook_event_type(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ let webhook = RecurlyWebhookBody::get_webhook_object_from_body(request.body)
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+ let event = match webhook.event_type {
+ transformers::RecurlyPaymentEventType::PaymentSucceeded => {
+ api_models::webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess
+ }
+ transformers::RecurlyPaymentEventType::PaymentFailed => {
+ api_models::webhooks::IncomingWebhookEvent::RecoveryPaymentFailure
+ }
+ };
+ Ok(event)
+ }
+
+ #[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))]
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
@@ -559,9 +649,11 @@ impl webhooks::IncomingWebhook for Recurly {
fn get_webhook_resource_object(
&self,
- _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ let webhook = RecurlyWebhookBody::get_webhook_object_from_body(request.body)
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+ Ok(Box::new(webhook))
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
index bc62985edb3..8b7c9b65c69 100644
--- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs
@@ -1,5 +1,6 @@
use common_enums::enums;
-use common_utils::types::StringMinorUnit;
+use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, types::StringMinorUnit};
+use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
@@ -226,3 +227,27 @@ pub struct RecurlyErrorResponse {
pub message: String,
pub reason: Option<String>,
}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct RecurlyWebhookBody {
+ // transaction id
+ pub uuid: String,
+ pub event_type: RecurlyPaymentEventType,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub enum RecurlyPaymentEventType {
+ #[serde(rename = "succeeded")]
+ PaymentSucceeded,
+ #[serde(rename = "failed")]
+ PaymentFailed,
+}
+
+impl RecurlyWebhookBody {
+ pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
+ let webhook_body = body
+ .parse_struct::<Self>("RecurlyWebhookBody")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+ Ok(webhook_body)
+ }
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 22689511514..0da8bbf1828 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -14,7 +14,7 @@ use diesel_models::configs;
#[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))]
use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};
use error_stack::{report, FutureExt, ResultExt};
-use hyperswitch_connectors::connectors::chargebee;
+use hyperswitch_connectors::connectors::{chargebee, recurly};
use hyperswitch_domain_models::merchant_connector_account::{
FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount,
};
@@ -1535,6 +1535,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {
razorpay::transformers::RazorpayAuthType::try_from(self.auth_type)?;
Ok(())
}
+ api_enums::Connector::Recurly => {
+ recurly::transformers::RecurlyAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Shift4 => {
shift4::transformers::Shift4AuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index c6af87aa2be..9499eed165b 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -526,7 +526,9 @@ impl ConnectorData {
enums::Connector::Rapyd => {
Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new())))
}
- // enums::Connector::Recurly => Ok(ConnectorEnum::Old(Box::new(connector::Recurly))),
+ enums::Connector::Recurly => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Recurly::new())))
+ }
// enums::Connector::Redsys => Ok(ConnectorEnum::Old(Box::new(connector::Redsys))),
enums::Connector::Shift4 => {
Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new())))
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 39f6afcfc9c..2fa29ccaf96 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -296,7 +296,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Prophetpay => Self::Prophetpay,
api_enums::Connector::Rapyd => Self::Rapyd,
api_enums::Connector::Razorpay => Self::Razorpay,
- // api_enums::Connector::Recurly => Self::Recurly,
+ api_enums::Connector::Recurly => Self::Recurly,
// api_enums::Connector::Redsys => Self::Redsys,
api_enums::Connector::Shift4 => Self::Shift4,
api_enums::Connector::Signifyd => {
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 09b9ccfb033..747f5365e01 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -157,7 +157,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
razorpay.base_url = "https://sandbox.juspay.in/"
-recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com"
+recurly.base_url = "https://v3.recurly.com"
redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago"
riskified.base_url = "https://sandbox.riskified.com/api"
shift4.base_url = "https://api.shift4.com/"
|
feat
|
Recurly incoming webhook support (#7439)
|
ccf032732e754480ed3c934a1eb9e24089be43a6
|
2023-04-11 15:29:38
|
JeevaRamu0104
|
refactor(refund_type): Feat/add copy dervie (#849)
| false
|
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index 7c2b2c113a4..f2d49c417ef 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -150,7 +150,7 @@ pub struct RefundListResponse {
/// The status for refunds
#[derive(
- Debug, Eq, Clone, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display,
+ Debug, Eq, Clone, Copy, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display,
)]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
|
refactor
|
Feat/add copy dervie (#849)
|
9cc8b93070e111c7a4b5beb1ee3bd2e51d96f2ca
|
2023-11-08 12:56:41
|
Chethan Rao
|
ci: checkout repo before spell checking pr title (#2776)
| false
|
diff --git a/.github/workflows/pr-title-check.yml b/.github/workflows/conventional-commit-check.yml
similarity index 89%
rename from .github/workflows/pr-title-check.yml
rename to .github/workflows/conventional-commit-check.yml
index 167be295443..5fd25e9332d 100644
--- a/.github/workflows/pr-title-check.yml
+++ b/.github/workflows/conventional-commit-check.yml
@@ -1,4 +1,4 @@
-name: PR Title Checks
+name: Conventional Commit Message Check
on:
# This is a dangerous event trigger as it causes the workflow to run in the
@@ -35,21 +35,6 @@ env:
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
jobs:
- typos:
- name: Spell check PR title
- runs-on: ubuntu-latest
- steps:
- - name: Store PR title in a file
- shell: bash
- env:
- TITLE: ${{ github.event.pull_request.title }}
- run: echo $TITLE > pr_title.txt
-
- - name: Spell check
- uses: crate-ci/typos@master
- with:
- files: ./pr_title.txt
-
pr_title_check:
name: Verify PR title follows conventional commit standards
runs-on: ubuntu-latest
diff --git a/.github/workflows/pr-title-spell-check.yml b/.github/workflows/pr-title-spell-check.yml
new file mode 100644
index 00000000000..6ab6f184739
--- /dev/null
+++ b/.github/workflows/pr-title-spell-check.yml
@@ -0,0 +1,27 @@
+name: PR Title Spell Check
+
+on:
+ pull_request:
+ types:
+ - opened
+ - edited
+ - synchronize
+
+jobs:
+ typos:
+ name: Spell check PR title
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+
+ - name: Store PR title in a file
+ shell: bash
+ env:
+ TITLE: ${{ github.event.pull_request.title }}
+ run: echo $TITLE > pr_title.txt
+
+ - name: Spell check
+ uses: crate-ci/typos@master
+ with:
+ files: ./pr_title.txt
|
ci
|
checkout repo before spell checking pr title (#2776)
|
ae5290fe8c7da6fe83083bd9e5bb41fad583d03c
|
2024-02-06 05:48:38
|
github-actions
|
chore(version): 2024.02.06.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a12f5bc65d..9a8dacda01a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,23 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.02.06.0
+
+### Features
+
+- **connector:** [Adyen] Use connector_request_reference_id as reference to Payments ([#3547](https://github.com/juspay/hyperswitch/pull/3547)) ([`c2eecce`](https://github.com/juspay/hyperswitch/commit/c2eecce1e803de308dcfcf774aa8aa2323cc96ec))
+
+### Bug Fixes
+
+- **connector:** [NMI] Handle empty response in psync and error response in complete authorize ([#3548](https://github.com/juspay/hyperswitch/pull/3548)) ([`a0fcef3`](https://github.com/juspay/hyperswitch/commit/a0fcef3f04cab75cf05154ef16fd26ab5a3783b9))
+- **router:** Handle empty body parse failures in bad request logger middleware ([#3541](https://github.com/juspay/hyperswitch/pull/3541)) ([`be22d60`](https://github.com/juspay/hyperswitch/commit/be22d60ddac18d9fb3032f72247634799e8f4ceb))
+- Add `profile_id` in dispute ([#3486](https://github.com/juspay/hyperswitch/pull/3486)) ([`0d5cd71`](https://github.com/juspay/hyperswitch/commit/0d5cd711b245fb69d0f35830aa1ba2f0b8a297cc))
+- Return currency in payment methods list response ([#3516](https://github.com/juspay/hyperswitch/pull/3516)) ([`a9c0d0c`](https://github.com/juspay/hyperswitch/commit/a9c0d0c55492c14a4a10283ffd8deae04c8ea853))
+
+**Full Changelog:** [`2024.02.05.0...2024.02.06.0`](https://github.com/juspay/hyperswitch/compare/2024.02.05.0...2024.02.06.0)
+
+- - -
+
## 2024.02.05.0
### Features
|
chore
|
2024.02.06.0
|
4e8de46423829a46c787ed9b7e015ce2680692be
|
2023-12-11 13:24:25
|
github-actions
|
chore(version): v1.98.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6bfcc08d08e..62ed03591ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,42 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.98.0 (2023-12-11)
+
+### Features
+
+- **connector:** Accept connector_transaction_id in error_response of connector flows for Trustpay ([#3060](https://github.com/juspay/hyperswitch/pull/3060)) ([`f53b090`](https://github.com/juspay/hyperswitch/commit/f53b090db87e094f9694481f13af62240c4c422a))
+- **pm_auth:** Pm_auth service migration ([#3047](https://github.com/juspay/hyperswitch/pull/3047)) ([`9c1c44a`](https://github.com/juspay/hyperswitch/commit/9c1c44a706750b14857e9180f5161b61ed89a2ad))
+- **user:** Add `verify_email` API ([#3076](https://github.com/juspay/hyperswitch/pull/3076)) ([`585e009`](https://github.com/juspay/hyperswitch/commit/585e00980c43797f326efb809df9ffd497d1dd26))
+- **users:** Add resend verification email API ([#3093](https://github.com/juspay/hyperswitch/pull/3093)) ([`6d5c25e`](https://github.com/juspay/hyperswitch/commit/6d5c25e3369117acaf5865965769649d524226af))
+
+### Bug Fixes
+
+- **analytics:** Adding api_path to api logs event and to auditlogs api response ([#3079](https://github.com/juspay/hyperswitch/pull/3079)) ([`bf67438`](https://github.com/juspay/hyperswitch/commit/bf674380d5c7e856d0bae75554326aa9017c0201))
+- **config:** Add missing config fields in `docker_compose.toml` ([#3080](https://github.com/juspay/hyperswitch/pull/3080)) ([`1f8116d`](https://github.com/juspay/hyperswitch/commit/1f8116db368aec344d08603045c4cb46c2c25b41))
+- **connector:** [CYBERSOURCE] Remove Phone Number Field From Address ([#3095](https://github.com/juspay/hyperswitch/pull/3095)) ([`72955ec`](https://github.com/juspay/hyperswitch/commit/72955ecc68280773b9c77b4db3d46de95a62f9ed))
+- **drainer:** Properly log deserialization errors ([#3075](https://github.com/juspay/hyperswitch/pull/3075)) ([`42b5bd4`](https://github.com/juspay/hyperswitch/commit/42b5bd4f3d142c9fa12475f36a8b144753ac06e2))
+- **router:** Allow zero amount for payment intent in list payment methods ([#3090](https://github.com/juspay/hyperswitch/pull/3090)) ([`b283b6b`](https://github.com/juspay/hyperswitch/commit/b283b6b662c9f2eabe90473434369d8f7c2369a6))
+- **user:** Add checks for change password ([#3078](https://github.com/juspay/hyperswitch/pull/3078)) ([`26a2611`](https://github.com/juspay/hyperswitch/commit/26a261131b4dbb8570e139127a2c0d356e2820be))
+
+### Refactors
+
+- **payment_methods:** Make the card_holder_name optional for card details in the payment APIs ([#3074](https://github.com/juspay/hyperswitch/pull/3074)) ([`b279591`](https://github.com/juspay/hyperswitch/commit/b279591057cdba6004c99efc82bb856f0bacd1e0))
+- **user:** Add account verification check in signin ([#3082](https://github.com/juspay/hyperswitch/pull/3082)) ([`f7d6e3c`](https://github.com/juspay/hyperswitch/commit/f7d6e3c0149869175a59996e67d3e2d3b6f3b8c2))
+
+### Documentation
+
+- **openapi:** Fix `payment_methods_enabled` OpenAPI spec in merchant connector account APIs ([#3068](https://github.com/juspay/hyperswitch/pull/3068)) ([`b6838c4`](https://github.com/juspay/hyperswitch/commit/b6838c4d1a3a456e28a5f438fcd74a60bedb2539))
+
+### Miscellaneous Tasks
+
+- **configs:** [CYBERSOURCE] Add mandate configs ([#3085](https://github.com/juspay/hyperswitch/pull/3085)) ([`777cd5c`](https://github.com/juspay/hyperswitch/commit/777cd5cdc2342fb7195a06505647fa331725e1dd))
+
+**Full Changelog:** [`v1.97.0...v1.98.0`](https://github.com/juspay/hyperswitch/compare/v1.97.0...v1.98.0)
+
+- - -
+
+
## 1.97.0 (2023-12-06)
### Features
|
chore
|
v1.98.0
|
4ef3420ee8ad39ee28a0fb496b30fe2a7e108813
|
2024-08-02 05:47:33
|
github-actions
|
chore(version): 2024.08.02.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f586793f54b..5b9b3ca974a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,33 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.08.02.0
+
+### Features
+
+- **auth:**
+ - Add support for partial-auth, by facilitating injection of authentication parameters in headers ([#4802](https://github.com/juspay/hyperswitch/pull/4802)) ([`1d4c87a`](https://github.com/juspay/hyperswitch/commit/1d4c87a9e37ab1fc05754208ba4fbbcf15ad895a))
+ - Add `profile_id` in `AuthenticationData` ([#5492](https://github.com/juspay/hyperswitch/pull/5492)) ([`b4eb601`](https://github.com/juspay/hyperswitch/commit/b4eb6016a4e696acf155732592a6571363c24e64))
+- **business_profile:** Introduce domain models for business profile v1 and v2 APIs ([#5497](https://github.com/juspay/hyperswitch/pull/5497)) ([`537630f`](https://github.com/juspay/hyperswitch/commit/537630f00482939d4c0b49c643dee3763fe0e046))
+- **connector:** [Paybox] add connector template code ([#5485](https://github.com/juspay/hyperswitch/pull/5485)) ([`5e1eb4a`](https://github.com/juspay/hyperswitch/commit/5e1eb4af863265c94299189de983e02a255e7e62))
+- **core:** Accept business profile in core functions for payments, refund, payout and disputes ([#5498](https://github.com/juspay/hyperswitch/pull/5498)) ([`fb32b61`](https://github.com/juspay/hyperswitch/commit/fb32b61edfa2b4190a5717850aeca6b3b0d7db54))
+- **cypress:** Add corner cases ([#5481](https://github.com/juspay/hyperswitch/pull/5481)) ([`c0f4577`](https://github.com/juspay/hyperswitch/commit/c0f45771b0b4d7d60918ae03aca9f14162ff3218))
+- **opensearch:** Updated status filter field name to match index and added time-range based search ([#5468](https://github.com/juspay/hyperswitch/pull/5468)) ([`625f5ae`](https://github.com/juspay/hyperswitch/commit/625f5ae289ca93a1a6d469d6a0f71d7492f22bc5))
+
+### Bug Fixes
+
+- **open_payment_links:** Send displaySavedPaymentMethods as false explicitly for open payment links ([#5501](https://github.com/juspay/hyperswitch/pull/5501)) ([`b4e7717`](https://github.com/juspay/hyperswitch/commit/b4e77170559d5912758f18d2db46bf25eb5277b2))
+
+### Refactors
+
+- **role:** Determine level of role entity ([#5488](https://github.com/juspay/hyperswitch/pull/5488)) ([`c036fd7`](https://github.com/juspay/hyperswitch/commit/c036fd7f41a21eb481859671db672b0bcebdca97))
+- **router:** Domain and diesel model changes for merchant_connector_account create v2 flow ([#5462](https://github.com/juspay/hyperswitch/pull/5462)) ([`85209d1`](https://github.com/juspay/hyperswitch/commit/85209d12ae3439b555983d62b2cc3bf764c1b441))
+- **routing:** Api v2 for routing create and activate endpoints ([#5423](https://github.com/juspay/hyperswitch/pull/5423)) ([`6140cfe`](https://github.com/juspay/hyperswitch/commit/6140cfe04ea7b3f895f8989dbf2803a06b1a6dd2))
+
+**Full Changelog:** [`2024.08.01.0...2024.08.02.0`](https://github.com/juspay/hyperswitch/compare/2024.08.01.0...2024.08.02.0)
+
+- - -
+
## 2024.08.01.0
### Bug Fixes
|
chore
|
2024.08.02.0
|
664093dc79743203196d912c17570885718b1c02
|
2023-10-23 00:27:54
|
Himanshu Singh
|
refactor(connector): [PowerTranz] refactor powertranz payments to remove default cases (#2547)
| false
|
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 4032f8019b0..5bbfe094352 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -1,6 +1,7 @@
use api_models::payments::Card;
use common_utils::pii::Email;
use diesel_models::enums::RefundStatus;
+use error_stack::IntoReport;
use masking::Secret;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -101,9 +102,22 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let source = match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(card) => Ok(Source::from(&card)),
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- )),
+ api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "powertranz",
+ })
+ .into_report(),
}?;
// let billing_address = get_address_details(&item.address.billing, &item.request.email);
// let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
|
refactor
|
[PowerTranz] refactor powertranz payments to remove default cases (#2547)
|
006e9a88927ff619ee24ebcbb66eac34afbe66ca
|
2023-01-16 23:58:21
|
Manoj Ghorela
|
feat(connector_integration): integrate Rapyd connector (#357)
| false
|
diff --git a/config/Development.toml b/config/Development.toml
index e0315b066fc..761156a9a37 100644
--- a/config/Development.toml
+++ b/config/Development.toml
@@ -82,6 +82,9 @@ base_url = "https://apitest.cybersource.com/"
[connectors.shift4]
base_url = "https://api.shift4.com/"
+[connectors.rapyd]
+base_url = "https://sandboxapi.rapyd.net"
+
[connectors.fiserv]
base_url = "https://cert.api.fiservapps.com/"
@@ -90,6 +93,7 @@ base_url = "http://localhost:9090/"
[connectors.payu]
base_url = "https://secure.snd.payu.com/api/"
+
[connectors.globalpay]
base_url = "https://apis.sandbox.globalpay.com/ucp/"
diff --git a/config/config.example.toml b/config/config.example.toml
index 6bedd98ab23..ed90f403192 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -133,6 +133,9 @@ base_url = "https://apitest.cybersource.com/"
[connectors.shift4]
base_url = "https://api.shift4.com/"
+[connectors.rapyd]
+base_url = "https://sandboxapi.rapyd.net"
+
[connectors.fiserv]
base_url = "https://cert.api.fiservapps.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index d38380b73c8..bf6ec07b306 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -85,6 +85,9 @@ base_url = "https://apitest.cybersource.com/"
[connectors.shift4]
base_url = "https://api.shift4.com/"
+[connectors.rapyd]
+base_url = "https://sandboxapi.rapyd.net"
+
[connectors.fiserv]
base_url = "https://cert.api.fiservapps.com/"
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 0c77ca85bff..c24b915e324 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -507,6 +507,7 @@ pub enum Connector {
Globalpay,
Klarna,
Payu,
+ Rapyd,
Shift4,
Stripe,
Worldline,
diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml
index 5e447f2775d..437f78eed23 100644
--- a/crates/router/src/configs/defaults.toml
+++ b/crates/router/src/configs/defaults.toml
@@ -63,4 +63,4 @@ max_read_count = 100
[connectors.supported]
wallets = ["klarna","braintree"]
-cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource", "fiserv"]
+cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource", "fiserv", "rapyd"]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 1f66cb22ff2..72b641f9ae8 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -131,6 +131,7 @@ pub struct Connectors {
pub globalpay: ConnectorParams,
pub klarna: ConnectorParams,
pub payu: ConnectorParams,
+ pub rapyd: ConnectorParams,
pub shift4: ConnectorParams,
pub stripe: ConnectorParams,
pub supported: SupportedConnectors,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 4c218454d99..a692e1e48c5 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -9,6 +9,7 @@ pub mod fiserv;
pub mod globalpay;
pub mod klarna;
pub mod payu;
+pub mod rapyd;
pub mod shift4;
pub mod stripe;
pub mod utils;
@@ -18,6 +19,6 @@ pub mod worldpay;
pub use self::{
aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet,
braintree::Braintree, checkout::Checkout, cybersource::Cybersource, fiserv::Fiserv,
- globalpay::Globalpay, klarna::Klarna, payu::Payu, shift4::Shift4, stripe::Stripe,
+ globalpay::Globalpay, klarna::Klarna, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe,
worldline::Worldline, worldpay::Worldpay,
};
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
new file mode 100644
index 00000000000..b6f35e1a93d
--- /dev/null
+++ b/crates/router/src/connector/rapyd.rs
@@ -0,0 +1,656 @@
+mod transformers;
+use std::fmt::Debug;
+
+use base64::Engine;
+use bytes::Bytes;
+use common_utils::date_time;
+use error_stack::{IntoReport, ResultExt};
+use rand::distributions::{Alphanumeric, DistString};
+use ring::hmac;
+use transformers as rapyd;
+
+use crate::{
+ configs::settings,
+ consts,
+ core::{
+ errors::{self, CustomResult},
+ payments,
+ },
+ headers, logger, services,
+ types::{
+ self,
+ api::{self, ConnectorCommon},
+ ErrorResponse, Response,
+ },
+ utils::{self, BytesExt},
+};
+
+#[derive(Debug, Clone)]
+pub struct Rapyd;
+
+impl Rapyd {
+ pub fn generate_signature(
+ &self,
+ auth: &rapyd::RapydAuthType,
+ http_method: &str,
+ url_path: &str,
+ body: &str,
+ timestamp: &i64,
+ salt: &str,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let rapyd::RapydAuthType {
+ access_key,
+ secret_key,
+ } = auth;
+ let to_sign =
+ format!("{http_method}{url_path}{salt}{timestamp}{access_key}{secret_key}{body}");
+ let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
+ let tag = hmac::sign(&key, to_sign.as_bytes());
+ let hmac_sign = hex::encode(tag);
+ let signature_value = consts::BASE64_ENGINE_URL_SAFE.encode(hmac_sign);
+ Ok(signature_value)
+ }
+}
+
+impl ConnectorCommon for Rapyd {
+ fn id(&self) -> &'static str {
+ "rapyd"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.rapyd.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ _auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![])
+ }
+}
+
+impl api::PaymentAuthorize for Rapyd {}
+
+impl
+ services::ConnectorIntegration<
+ api::Authorize,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ > for Rapyd
+{
+ fn get_headers(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsAuthorizeType::get_content_type(self).to_string(),
+ )])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/v1/payments", self.base_url(connectors)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RouterData<
+ api::Authorize,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let timestamp = date_time::now_unix_timestamp();
+ let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
+
+ let rapyd_req = utils::Encode::<rapyd::RapydPaymentsRequest>::convert_and_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
+ let signature =
+ self.generate_signature(&auth, "post", "/v1/payments", &rapyd_req, ×tamp, &salt)?;
+ let headers = vec![
+ ("access_key".to_string(), auth.access_key),
+ ("salt".to_string(), salt),
+ ("timestamp".to_string(), timestamp.to_string()),
+ ("signature".to_string(), signature),
+ ];
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .headers(headers)
+ .body(Some(rapyd_req))
+ .build();
+ Ok(Some(request))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let rapyd_req = utils::Encode::<rapyd::RapydPaymentsRequest>::convert_and_url_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(rapyd_req))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .response
+ .parse_struct("Rapyd PaymentResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(rapydpayments_create_response=?response);
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Bytes,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .parse_struct("Rapyd ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(ErrorResponse {
+ code: response.status.error_code,
+ message: response.status.status,
+ reason: response.status.message,
+ })
+ }
+}
+
+impl api::Payment for Rapyd {}
+
+impl api::PreVerify for Rapyd {}
+impl
+ services::ConnectorIntegration<
+ api::Verify,
+ types::VerifyRequestData,
+ types::PaymentsResponseData,
+ > for Rapyd
+{
+}
+
+impl api::PaymentVoid for Rapyd {}
+
+impl
+ services::ConnectorIntegration<
+ api::Void,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ > for Rapyd
+{
+ fn get_headers(
+ &self,
+ _req: &types::PaymentsCancelRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsVoidType::get_content_type(self).to_string(),
+ )])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}/v1/payments/{}",
+ self.base_url(connectors),
+ req.request.connector_transaction_id
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let timestamp = date_time::now_unix_timestamp();
+ let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
+
+ let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
+ let url_path = format!("/v1/payments/{}", req.request.connector_transaction_id);
+ let signature =
+ self.generate_signature(&auth, "delete", &url_path, "", ×tamp, &salt)?;
+
+ let headers = vec![
+ ("access_key".to_string(), auth.access_key),
+ ("salt".to_string(), salt),
+ ("timestamp".to_string(), timestamp.to_string()),
+ ("signature".to_string(), signature),
+ ];
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Delete)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .headers(headers)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCancelRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .response
+ .parse_struct("Rapyd PaymentResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(rapydpayments_create_response=?response);
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Bytes,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .parse_struct("Rapyd ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(ErrorResponse {
+ code: response.status.error_code,
+ message: response.status.status,
+ reason: response.status.message,
+ })
+ }
+}
+
+impl api::PaymentSync for Rapyd {}
+impl
+ services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Rapyd
+{
+ fn get_headers(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("PSync".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(None)
+ }
+
+ fn get_error_response(
+ &self,
+ _res: Bytes,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("PSync".to_string()).into())
+ }
+
+ fn handle_response(
+ &self,
+ _data: &types::PaymentsSyncRouterData,
+ _res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("PSync".to_string()).into())
+ }
+}
+
+impl api::PaymentCapture for Rapyd {}
+impl
+ services::ConnectorIntegration<
+ api::Capture,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ > for Rapyd
+{
+ fn get_headers(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsCaptureType::get_content_type(self).to_string(),
+ )])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let rapyd_req = utils::Encode::<rapyd::CaptureRequest>::convert_and_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(rapyd_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let timestamp = date_time::now_unix_timestamp();
+ let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
+
+ let rapyd_req = utils::Encode::<rapyd::CaptureRequest>::convert_and_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
+ let url_path = format!(
+ "/v1/payments/{}/capture",
+ req.request.connector_transaction_id
+ );
+ let signature =
+ self.generate_signature(&auth, "post", &url_path, &rapyd_req, ×tamp, &salt)?;
+ let headers = vec![
+ ("access_key".to_string(), auth.access_key),
+ ("salt".to_string(), salt),
+ ("timestamp".to_string(), timestamp.to_string()),
+ ("signature".to_string(), signature),
+ ];
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .headers(headers)
+ .body(Some(rapyd_req))
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .response
+ .parse_struct("RapydPaymentResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}/v1/payments/{}/capture",
+ self.base_url(connectors),
+ req.request.connector_transaction_id
+ ))
+ }
+
+ fn get_error_response(
+ &self,
+ res: Bytes,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .parse_struct("Rapyd ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(ErrorResponse {
+ code: response.status.error_code,
+ message: response.status.status,
+ reason: response.status.message,
+ })
+ }
+}
+
+impl api::PaymentSession for Rapyd {}
+
+impl
+ services::ConnectorIntegration<
+ api::Session,
+ types::PaymentsSessionData,
+ types::PaymentsResponseData,
+ > for Rapyd
+{
+ //TODO: implement sessions flow
+}
+
+impl api::Refund for Rapyd {}
+impl api::RefundExecute for Rapyd {}
+impl api::RefundSync for Rapyd {}
+
+impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
+ for Rapyd
+{
+ fn get_headers(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::RefundExecuteType::get_content_type(self).to_string(),
+ )])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ api::ConnectorCommon::common_get_content_type(self)
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/v1/refunds", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let rapyd_req = utils::Encode::<rapyd::RapydRefundRequest>::convert_and_url_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(rapyd_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let timestamp = date_time::now_unix_timestamp();
+ let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
+
+ let rapyd_req = utils::Encode::<rapyd::RapydRefundRequest>::convert_and_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?;
+ let signature =
+ self.generate_signature(&auth, "post", "/v1/refunds", &rapyd_req, ×tamp, &salt)?;
+ let headers = vec![
+ ("access_key".to_string(), auth.access_key),
+ ("salt".to_string(), salt),
+ ("timestamp".to_string(), timestamp.to_string()),
+ ("signature".to_string(), signature),
+ ];
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .headers(headers)
+ .body(Some(rapyd_req))
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ logger::debug!(target: "router::connector::rapyd", response=?res);
+ let response: rapyd::RefundResponse = res
+ .response
+ .parse_struct("rapyd RefundResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Bytes,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: rapyd::RapydPaymentsResponse = res
+ .parse_struct("Rapyd ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(ErrorResponse {
+ code: response.status.error_code,
+ message: response.status.status,
+ reason: response.status.message,
+ })
+ }
+}
+
+impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
+ for Rapyd
+{
+ fn get_headers(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![])
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("RSync".to_string()).into())
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ logger::debug!(target: "router::connector::rapyd", response=?res);
+ let response: rapyd::RefundResponse = res
+ .response
+ .parse_struct("rapyd RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ _res: Bytes,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("RSync".to_string()).into())
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Rapyd {
+ fn get_webhook_object_reference_id(
+ &self,
+ _body: &[u8],
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _body: &[u8],
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _body: &[u8],
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+}
+
+impl services::ConnectorRedirectResponse for Rapyd {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+}
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
new file mode 100644
index 00000000000..f2bd8315253
--- /dev/null
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -0,0 +1,481 @@
+use error_stack::{IntoReport, ResultExt};
+use serde::{Deserialize, Serialize};
+use url::Url;
+
+use crate::{
+ core::errors,
+ pii::{self, Secret},
+ services,
+ types::{
+ self, api,
+ storage::enums,
+ transformers::{self, ForeignFrom},
+ },
+};
+
+#[derive(Default, Debug, Serialize)]
+pub struct RapydPaymentsRequest {
+ pub amount: i64,
+ pub currency: enums::Currency,
+ pub payment_method: PaymentMethod,
+ pub payment_method_options: PaymentMethodOptions,
+ pub capture: bool,
+}
+
+#[derive(Default, Debug, Serialize)]
+pub struct PaymentMethodOptions {
+ #[serde(rename = "3d_required")]
+ pub three_ds: bool,
+}
+#[derive(Default, Debug, Serialize)]
+pub struct PaymentMethod {
+ #[serde(rename = "type")]
+ pub pm_type: String,
+ pub fields: PaymentFields,
+}
+
+#[derive(Default, Debug, Serialize)]
+pub struct PaymentFields {
+ pub number: Secret<String, pii::CardNumber>,
+ pub expiration_month: Secret<String>,
+ pub expiration_year: Secret<String>,
+ pub name: Secret<String>,
+ pub cvv: Secret<String>,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data {
+ api_models::payments::PaymentMethod::Card(ref ccard) => {
+ let payment_method = PaymentMethod {
+ pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country
+ fields: PaymentFields {
+ number: ccard.card_number.to_owned(),
+ expiration_month: ccard.card_exp_month.to_owned(),
+ expiration_year: ccard.card_exp_year.to_owned(),
+ name: ccard.card_holder_name.to_owned(),
+ cvv: ccard.card_cvc.to_owned(),
+ },
+ };
+ let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs);
+ let payment_method_options = PaymentMethodOptions {
+ three_ds: three_ds_enabled,
+ };
+ Ok(Self {
+ amount: item.request.amount,
+ currency: item.request.currency,
+ payment_method,
+ capture: matches!(
+ item.request.capture_method,
+ Some(enums::CaptureMethod::Automatic) | None
+ ),
+ payment_method_options,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+pub struct RapydAuthType {
+ pub access_key: String,
+ pub secret_key: String,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for RapydAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ Ok(Self {
+ access_key: api_key.to_string(),
+ secret_key: key1.to_string(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType)?
+ }
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[allow(clippy::upper_case_acronyms)]
+pub enum RapydPaymentStatus {
+ #[serde(rename = "ACT")]
+ Active,
+ #[serde(rename = "CAN")]
+ CanceledByClientOrBank,
+ #[serde(rename = "CLO")]
+ Closed,
+ #[serde(rename = "ERR")]
+ Error,
+ #[serde(rename = "EXP")]
+ Expired,
+ #[serde(rename = "REV")]
+ ReversedByRapyd,
+ #[default]
+ #[serde(rename = "NEW")]
+ New,
+}
+
+impl From<transformers::Foreign<(RapydPaymentStatus, String)>>
+ for transformers::Foreign<enums::AttemptStatus>
+{
+ fn from(item: transformers::Foreign<(RapydPaymentStatus, String)>) -> Self {
+ let (status, next_action) = item.0;
+ match status {
+ RapydPaymentStatus::Closed => enums::AttemptStatus::Charged,
+ RapydPaymentStatus::Active => {
+ if next_action == "3d_verification" {
+ enums::AttemptStatus::AuthenticationPending
+ } else if next_action == "pending_capture" {
+ enums::AttemptStatus::Authorized
+ } else {
+ enums::AttemptStatus::Pending
+ }
+ }
+ RapydPaymentStatus::CanceledByClientOrBank
+ | RapydPaymentStatus::Error
+ | RapydPaymentStatus::Expired
+ | RapydPaymentStatus::ReversedByRapyd => enums::AttemptStatus::Failure,
+ RapydPaymentStatus::New => enums::AttemptStatus::Authorizing,
+ }
+ .into()
+ }
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct RapydPaymentsResponse {
+ pub status: Status,
+ pub data: Option<ResponseData>,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct Status {
+ pub error_code: String,
+ pub status: String,
+ pub message: Option<String>,
+ pub response_code: Option<String>,
+ pub operation_id: String,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct ResponseData {
+ pub id: String,
+ pub amount: i64,
+ pub status: RapydPaymentStatus,
+ pub next_action: String,
+ pub redirect_url: Option<String>,
+ pub original_amount: Option<i64>,
+ pub is_partial: Option<bool>,
+ pub currency_code: Option<enums::Currency>,
+ pub country_code: Option<String>,
+ pub captured: Option<bool>,
+ pub transaction_id: String,
+ pub paid: Option<bool>,
+ pub failure_code: Option<String>,
+ pub failure_message: Option<String>,
+}
+
+impl TryFrom<types::PaymentsResponseRouterData<RapydPaymentsResponse>>
+ for types::PaymentsAuthorizeRouterData
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::PaymentsResponseRouterData<RapydPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ let (status, response) = match item.response.status.status.as_str() {
+ "SUCCESS" => match item.response.data {
+ Some(data) => {
+ let redirection_data = match (data.next_action.as_str(), data.redirect_url) {
+ ("3d_verification", Some(url)) => {
+ let url = Url::parse(&url)
+ .into_report()
+ .change_context(errors::ParsingError)?;
+ let mut base_url = url.clone();
+ base_url.set_query(None);
+ Some(services::RedirectForm {
+ url: base_url.to_string(),
+ method: services::Method::Get,
+ form_fields: std::collections::HashMap::from_iter(
+ url.query_pairs()
+ .map(|(k, v)| (k.to_string(), v.to_string())),
+ ),
+ })
+ }
+ (_, _) => None,
+ };
+ (
+ enums::AttemptStatus::foreign_from((data.status, data.next_action)),
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(data.id), //transaction_id is also the field but this id is used to initiate a refund
+ redirect: redirection_data.is_some(),
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata: None,
+ }),
+ )
+ }
+ None => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ },
+ "ERROR" => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ _ => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ };
+
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize)]
+pub struct RapydRefundRequest {
+ pub payment: String,
+ pub amount: Option<i64>,
+ pub currency: Option<enums::Currency>,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for RapydRefundRequest {
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment: item.request.connector_transaction_id.to_string(),
+ amount: Some(item.request.amount),
+ currency: Some(item.request.currency),
+ })
+ }
+}
+
+#[allow(dead_code)]
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+pub enum RefundStatus {
+ Completed,
+ Error,
+ Rejected,
+ #[default]
+ Pending,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Completed => Self::Success,
+ RefundStatus::Error | RefundStatus::Rejected => Self::Failure,
+ RefundStatus::Pending => Self::Pending,
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ pub status: Status,
+ pub data: Option<RefundResponseData>,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct RefundResponseData {
+ //Some field related to forign exchange and split payment can be added as and when implemented
+ pub id: String,
+ pub payment: String,
+ pub amount: i64,
+ pub currency: enums::Currency,
+ pub status: RefundStatus,
+ pub created_at: Option<i64>,
+ pub failure_reason: Option<String>,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ let (connector_refund_id, refund_status) = match item.response.data {
+ Some(data) => (data.id, enums::RefundStatus::from(data.status)),
+ None => (
+ item.response.status.error_code,
+ enums::RefundStatus::Failure,
+ ),
+ };
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ let (connector_refund_id, refund_status) = match item.response.data {
+ Some(data) => (data.id, enums::RefundStatus::from(data.status)),
+ None => (
+ item.response.status.error_code,
+ enums::RefundStatus::Failure,
+ ),
+ };
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Clone)]
+pub struct CaptureRequest {
+ amount: Option<i64>,
+ receipt_email: Option<String>,
+ statement_descriptor: Option<String>,
+}
+
+impl TryFrom<&types::PaymentsCaptureRouterData> for CaptureRequest {
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.request.amount_to_capture,
+ receipt_email: None,
+ statement_descriptor: None,
+ })
+ }
+}
+
+impl TryFrom<types::PaymentsCaptureResponseRouterData<RapydPaymentsResponse>>
+ for types::PaymentsCaptureRouterData
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::PaymentsCaptureResponseRouterData<RapydPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ let (status, response) = match item.response.status.status.as_str() {
+ "SUCCESS" => match item.response.data {
+ Some(data) => (
+ enums::AttemptStatus::foreign_from((data.status, data.next_action)),
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(data.id), //transaction_id is also the field but this id is used to initiate a refund
+ redirection_data: None,
+ redirect: false,
+ mandate_reference: None,
+ connector_metadata: None,
+ }),
+ ),
+ None => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ },
+ "ERROR" => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ _ => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ };
+
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::PaymentsCancelResponseRouterData<RapydPaymentsResponse>>
+ for types::PaymentsCancelRouterData
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::PaymentsCancelResponseRouterData<RapydPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ let (status, response) = match item.response.status.status.as_str() {
+ "SUCCESS" => match item.response.data {
+ Some(data) => (
+ enums::AttemptStatus::foreign_from((data.status, data.next_action)),
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(data.id), //transaction_id is also the field but this id is used to initiate a refund
+ redirection_data: None,
+ redirect: false,
+ mandate_reference: None,
+ connector_metadata: None,
+ }),
+ ),
+ None => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ },
+ "ERROR" => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ _ => (
+ enums::AttemptStatus::Failure,
+ Err(types::ErrorResponse {
+ code: item.response.status.error_code,
+ message: item.response.status.status,
+ reason: item.response.status.message,
+ }),
+ ),
+ };
+
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 687d7e6ac0e..3d30069981e 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -19,3 +19,6 @@ pub(crate) const NO_ERROR_CODE: &str = "No error code";
// General purpose base64 engine
pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose =
base64::engine::general_purpose::STANDARD;
+
+pub(crate) const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose =
+ base64::engine::general_purpose::URL_SAFE;
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 0c21a8a45ca..d8baef0eab5 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -150,6 +150,7 @@ impl ConnectorData {
"globalpay" => Ok(Box::new(&connector::Globalpay)),
"klarna" => Ok(Box::new(&connector::Klarna)),
"payu" => Ok(Box::new(&connector::Payu)),
+ "rapyd" => Ok(Box::new(&connector::Rapyd)),
"shift4" => Ok(Box::new(&connector::Shift4)),
"stripe" => Ok(Box::new(&connector::Stripe)),
"worldline" => Ok(Box::new(&connector::Worldline)),
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index 9bb2cabdcc3..0e74e936fde 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -9,6 +9,7 @@ pub(crate) struct ConnectorAuthentication {
pub fiserv: Option<SignatureKey>,
pub globalpay: Option<HeaderKey>,
pub payu: Option<BodyKey>,
+ pub rapyd: Option<BodyKey>,
pub shift4: Option<HeaderKey>,
pub worldpay: Option<HeaderKey>,
pub worldline: Option<SignatureKey>,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 39bb16e7a4b..2cd9aa7d240 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -7,6 +7,7 @@ mod connector_auth;
mod fiserv;
mod globalpay;
mod payu;
+mod rapyd;
mod shift4;
mod utils;
mod worldline;
diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs
new file mode 100644
index 00000000000..0625d3b08d3
--- /dev/null
+++ b/crates/router/tests/connectors/rapyd.rs
@@ -0,0 +1,144 @@
+use futures::future::OptionFuture;
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use serial_test::serial;
+
+use crate::{
+ connector_auth,
+ utils::{self, ConnectorActions},
+};
+
+struct Rapyd;
+impl ConnectorActions for Rapyd {}
+impl utils::Connector for Rapyd {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Rapyd;
+ types::api::ConnectorData {
+ connector: Box::new(&Rapyd),
+ connector_name: types::Connector::Rapyd,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .rapyd
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "rapyd".to_string()
+ }
+}
+
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = Rapyd {}
+ .authorize_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::CCard {
+ card_number: Secret::new("4111111111111111".to_string()),
+ card_exp_month: Secret::new("02".to_string()),
+ card_exp_year: Secret::new("2024".to_string()),
+ card_holder_name: Secret::new("John Doe".to_string()),
+ card_cvc: Secret::new("123".to_string()),
+ }),
+ capture_method: Some(storage_models::enums::CaptureMethod::Manual),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await;
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+#[actix_web::test]
+async fn should_authorize_and_capture_payment() {
+ let response = Rapyd {}
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::CCard {
+ card_number: Secret::new("4111111111111111".to_string()),
+ card_exp_month: Secret::new("02".to_string()),
+ card_exp_year: Secret::new("2024".to_string()),
+ card_holder_name: Secret::new("John Doe".to_string()),
+ card_cvc: Secret::new("123".to_string()),
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await;
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+#[actix_web::test]
+async fn should_capture_already_authorized_payment() {
+ let connector = Rapyd {};
+ let authorize_response = connector.authorize_payment(None, None).await;
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
+ let txn_id = utils::get_connector_transaction_id(authorize_response);
+ let response: OptionFuture<_> = txn_id
+ .map(|transaction_id| async move {
+ connector
+ .capture_payment(transaction_id, None, None)
+ .await
+ .status
+ })
+ .into();
+ assert_eq!(response.await, Some(enums::AttemptStatus::Charged));
+}
+
+#[actix_web::test]
+#[serial]
+async fn voiding_already_authorized_payment_fails() {
+ let connector = Rapyd {};
+ let authorize_response = connector.authorize_payment(None, None).await;
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
+ let txn_id = utils::get_connector_transaction_id(authorize_response);
+ let response: OptionFuture<_> = txn_id
+ .map(|transaction_id| async move {
+ connector
+ .void_payment(transaction_id, None, None)
+ .await
+ .status
+ })
+ .into();
+ assert_eq!(response.await, Some(enums::AttemptStatus::Failure)); //rapyd doesn't allow authorize transaction to be voided
+}
+
+#[actix_web::test]
+async fn should_refund_succeeded_payment() {
+ let connector = Rapyd {};
+ //make a successful payment
+ let response = connector.make_payment(None, None).await;
+
+ //try refund for previous payment
+ if let Some(transaction_id) = utils::get_connector_transaction_id(response) {
+ let response = connector.refund_payment(transaction_id, None, None).await;
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+ }
+}
+
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_card_number() {
+ let response = Rapyd {}
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::CCard {
+ card_number: Secret::new("0000000000000000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await;
+
+ assert!(response.response.is_err(), "The Payment pass");
+}
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index a161b71c078..fcb5c75df2f 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -26,6 +26,10 @@ key1 = "MerchantPosId"
[globalpay]
api_key = "Bearer MyApiKey"
+[rapyd]
+api_key = "access_key"
+key1 = "secret_key"
+
[fiserv]
api_key = "MyApiKey"
key1 = "MerchantID"
|
feat
|
integrate Rapyd connector (#357)
|
e757605fdc287685c573d0c1c461cea556e5a5ce
|
2024-08-13 14:59:37
|
Neeraj
|
docs(README): add social media links (#5600)
| false
|
diff --git a/README.md b/README.md
index 62e016d3620..f4729db9539 100644
--- a/README.md
+++ b/README.md
@@ -35,6 +35,17 @@ The single API to access payment ecosystems across 130+ countries</div>
<img src="https://img.shields.io/badge/Made_in-Rust-orange" />
</a>
</p>
+<p align="center">
+ <a href="https://www.linkedin.com/company/hyperswitch/">
+ <img src="https://img.shields.io/badge/follow-hyperswitch-blue?logo=linkedin&labelColor=grey"/>
+ </a>
+ <a href="https://x.com/hyperswitchio">
+ <img src="https://img.shields.io/badge/follow-%40hyperswitchio-white?logo=x&labelColor=grey"/>
+ </a>
+ <a href="https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw">
+ <img src="https://img.shields.io/badge/chat-on_slack-blue?logo=slack&labelColor=grey&color=%233f0e40"/>
+ </a>
+</p>
<hr>
<img src="./docs/imgs/switch.png" />
|
docs
|
add social media links (#5600)
|
304081cbadf86bbd5a20d69b96a79d6cd647024c
|
2023-04-21 02:50:29
|
Arjun Karthik
|
feat(router): add new payment methods for Bank redirects, BNPL and wallet (#864)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index d9999a69adc..94d137885dc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2767,7 +2767,7 @@ dependencies = [
[[package]]
name = "opentelemetry"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"opentelemetry_api",
"opentelemetry_sdk",
@@ -2776,7 +2776,7 @@ dependencies = [
[[package]]
name = "opentelemetry-otlp"
version = "0.11.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"async-trait",
"futures",
@@ -2793,7 +2793,7 @@ dependencies = [
[[package]]
name = "opentelemetry-proto"
version = "0.1.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"futures",
"futures-util",
@@ -2805,7 +2805,7 @@ dependencies = [
[[package]]
name = "opentelemetry_api"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"fnv",
"futures-channel",
@@ -2820,7 +2820,7 @@ dependencies = [
[[package]]
name = "opentelemetry_sdk"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"async-trait",
"crossbeam-channel",
diff --git a/config/development.toml b/config/development.toml
index 1a335764d67..7b5fc0b1f60 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -142,6 +142,12 @@ adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban
stripe = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" }
adyen = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" }
+[bank_config.online_banking_czech_republic]
+adyen = { banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"}
+
+[bank_config.online_banking_slovakia]
+adyen = { banks = "e_platby_v_u_b,postova_banka,sporo_pay,tatra_pay,viamo,volksbank_gruppe,volkskredit_bank_ag,vr_bank_braunau"}
+
[pm_filters.stripe]
google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" }
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 2d7cfe276a5..0aae07bb046 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -409,19 +409,34 @@ pub enum PaymentExperience {
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodType {
+ Affirm,
+ AfterpayClearpay,
+ AliPay,
+ ApplePay,
+ BancontactCard,
+ Blik,
Credit,
+ CryptoCurrency,
Debit,
+ Eps,
Giropay,
+ GooglePay,
Ideal,
- Sofort,
- Eps,
Klarna,
- Affirm,
- AfterpayClearpay,
- GooglePay,
- ApplePay,
+ MbWay,
+ MobilePay,
+ OnlineBankingCzechRepublic,
+ OnlineBankingFinland,
+ OnlineBankingPoland,
+ OnlineBankingSlovakia,
+ PayBright,
Paypal,
- CryptoCurrency,
+ Przelewy24,
+ Sofort,
+ Swish,
+ Trustly,
+ Walley,
+ WeChatPay,
}
#[derive(
@@ -684,6 +699,8 @@ pub enum BankNames {
AmericanExpress,
BankOfAmerica,
Barclays,
+ #[serde(rename = "BLIK - PSP")]
+ BlikPSP,
CapitalOne,
Chase,
Citi,
@@ -711,13 +728,21 @@ pub enum BankNames {
Bank99Ag,
BankhausCarlSpangler,
BankhausSchelhammerUndSchatteraAg,
+ #[serde(rename = "Bank Millennium")]
+ BankMillennium,
+ #[serde(rename = "Bank PEKAO S.A.")]
+ BankPEKAOSA,
BawagPskAg,
BksBankAg,
BrullKallmusBankAg,
BtvVierLanderBank,
CapitalBankGraweGruppeAg,
+ #[serde(rename = "Česká spořitelna")]
+ CeskaSporitelna,
Dolomitenbank,
EasybankAg,
+ #[serde(rename = "ePlatby VÚB")]
+ EPlatbyVUB,
ErsteBankUndSparkassen,
HypoAlpeadriabankInternationalAg,
HypoNoeLbFurNiederosterreichUWien,
@@ -725,17 +750,57 @@ pub enum BankNames {
HypoTirolBankAg,
HypoVorarlbergBankAg,
HypoBankBurgenlandAktiengesellschaft,
+ #[serde(rename = "Komercní banka")]
+ KomercniBanka,
+ #[serde(rename = "mBank - mTransfer")]
+ MBank,
MarchfelderBank,
OberbankAg,
OsterreichischeArzteUndApothekerbank,
+ #[serde(rename = "Pay with ING")]
+ PayWithING,
+ #[serde(rename = "Płacę z iPKO")]
+ PlaceZIPKO,
+ #[serde(rename = "Płatność online kartą płatniczą")]
+ PlatnoscOnlineKartaPlatnicza,
PosojilnicaBankEGen,
+ #[serde(rename = "Poštová banka")]
+ PostovaBanka,
RaiffeisenBankengruppeOsterreich,
SchelhammerCapitalBankAg,
SchoellerbankAg,
SpardaBankWien,
+ SporoPay,
+ #[serde(rename = "Santander-Przelew24")]
+ SantanderPrzelew24,
+ TatraPay,
+ Viamo,
VolksbankGruppe,
VolkskreditbankAg,
VrBankBraunau,
+ #[serde(rename = "Pay with Alior Bank")]
+ PayWithAliorBank,
+ #[serde(rename = "Banki Spółdzielcze")]
+ BankiSpoldzielcze,
+ #[serde(rename = "Pay with Inteligo")]
+ PayWithInteligo,
+ #[serde(rename = "BNP Paribas Poland")]
+ BNPParibasPoland,
+ #[serde(rename = "Bank Nowy S.A.")]
+ BankNowySA,
+ #[serde(rename = "Credit Agricole")]
+ CreditAgricole,
+ #[serde(rename = "Pay with BOŚ")]
+ PayWithBOS,
+ #[serde(rename = "Pay with CitiHandlowy")]
+ PayWithCitiHandlowy,
+ #[serde(rename = "Pay with Plus Bank")]
+ PayWithPlusBank,
+ #[serde(rename = "Toyota Bank")]
+ ToyotaBank,
+ VeloBank,
+ #[serde(rename = "e-transfer Pocztowy24")]
+ ETransferPocztowy24,
}
#[derive(
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index eefb27ee612..db2c7bd66ac 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -454,6 +454,8 @@ pub enum PayLaterData {
#[schema(value_type = String)]
billing_name: Secret<String>,
},
+ PayBright {},
+ Walley {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
@@ -510,6 +512,26 @@ impl From<&PaymentMethodData> for AdditionalPaymentData {
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BankRedirectData {
+ BancontactCard {
+ /// The card number
+ #[schema(value_type = String, example = "4242424242424242")]
+ card_number: Secret<String, pii::CardNumber>,
+ /// The card's expiry month
+ #[schema(value_type = String, example = "24")]
+ card_exp_month: Secret<String>,
+
+ /// The card's expiry year
+ #[schema(value_type = String, example = "24")]
+ card_exp_year: Secret<String>,
+
+ /// The card holder's name
+ #[schema(value_type = String, example = "John Test")]
+ card_holder_name: Secret<String>,
+ },
+ Blik {
+ // Blik Code
+ blik_code: String,
+ },
Eps {
/// The billing details for bank redirection
billing_details: BankRedirectBilling,
@@ -530,6 +552,23 @@ pub enum BankRedirectData {
#[schema(value_type = BankNames, example = "abn_amro")]
bank_name: api_enums::BankNames,
},
+ OnlineBankingCzechRepublic {
+ // Issuer banks
+ issuer: api_enums::BankNames,
+ },
+ OnlineBankingFinland {
+ // Shopper Email
+ email: Option<Secret<String, pii::Email>>,
+ },
+ OnlineBankingPoland {
+ // Issuer banks
+ issuer: api_enums::BankNames,
+ },
+ OnlineBankingSlovakia {
+ // Issuer value corresponds to the bank
+ issuer: api_enums::BankNames,
+ },
+ Przelewy24 {},
Sofort {
/// The billing details for bank redirection
billing_details: BankRedirectBilling,
@@ -542,6 +581,8 @@ pub enum BankRedirectData {
#[schema(example = "en")]
preferred_language: String,
},
+ Swish {},
+ Trustly {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
@@ -565,14 +606,21 @@ pub struct BankRedirectBilling {
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WalletData {
- /// The wallet data for Google pay
- GooglePay(GooglePayWalletData),
+ /// The wallet data for Ali Pay redirect
+ AliPay(AliPayRedirection),
/// The wallet data for Apple pay
ApplePay(ApplePayWalletData),
- /// The wallet data for Paypal
- PaypalSdk(PayPalWalletData),
+ /// The wallet data for Google pay
+ GooglePay(GooglePayWalletData),
+ MbWay(Box<MbWayRedirection>),
+ /// The wallet data for MobilePay redirect
+ MobilePay(Box<MobilePayRedirection>),
/// This is for paypal redirection
PaypalRedirect(PaypalRedirection),
+ /// The wallet data for Paypal
+ PaypalSdk(PayPalWalletData),
+ /// The wallet data for WeChat Pay Redirection
+ WeChatPayRedirect(Box<WeChatPayRedirection>),
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
@@ -588,9 +636,24 @@ pub struct GooglePayWalletData {
pub tokenization_data: GpayTokenizationData,
}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct WeChatPayRedirection {}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaypalRedirection {}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct AliPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct MobilePayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct MbWayRedirection {
+ /// Telephone number of the shopper. Should be Portuguese phone number.
+ pub telephone_number: Secret<String>,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GooglePayPaymentMethodInfo {
/// The name of the card network
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 621819b70a1..31d3740bf5e 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -191,6 +191,8 @@ impl
}
}
+/// Payment Sync can be useful only incase of Redirect flow.
+/// For payments which doesn't involve redrection we have to rely on webhooks.
impl
services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for Adyen
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index aa3c74f0b92..de5932fe63b 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -17,6 +17,8 @@ use crate::{
},
};
+type Error = error_stack::Report<errors::ConnectorError>;
+
// Adyen Types Definition
// Payments Request and Response Types
#[derive(Default, Debug, Serialize, Deserialize)]
@@ -115,19 +117,36 @@ struct AdyenBrowserInfo {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AdyenStatus {
+ AuthenticationFinished,
+ AuthenticationNotRequired,
Authorised,
- Refused,
Cancelled,
+ ChallengeShopper,
+ Error,
+ Pending,
+ Received,
RedirectShopper,
+ Refused,
}
-impl From<AdyenStatus> for storage_enums::AttemptStatus {
- fn from(item: AdyenStatus) -> Self {
- match item {
- AdyenStatus::Authorised => Self::Charged,
- AdyenStatus::Refused => Self::Failure,
+/// This implementation will be used only in Authorize, Automatic capture flow.
+/// It is also being used in Psync flow, However Psync will be called only after create payment call that too in redirect flow.
+impl ForeignFrom<(bool, AdyenStatus)> for storage_enums::AttemptStatus {
+ fn foreign_from((is_manual_capture, adyen_status): (bool, AdyenStatus)) -> Self {
+ match adyen_status {
+ AdyenStatus::AuthenticationFinished => Self::AuthenticationSuccessful,
+ AdyenStatus::AuthenticationNotRequired => Self::Pending,
+ AdyenStatus::Authorised => match is_manual_capture {
+ true => Self::Authorized,
+ false => Self::Charged,
+ },
AdyenStatus::Cancelled => Self::Voided,
- AdyenStatus::RedirectShopper => Self::AuthenticationPending,
+ AdyenStatus::ChallengeShopper | AdyenStatus::RedirectShopper => {
+ Self::AuthenticationPending
+ }
+ AdyenStatus::Error | AdyenStatus::Refused => Self::Failure,
+ AdyenStatus::Pending => Self::Pending,
+ AdyenStatus::Received => Self::Started,
}
}
}
@@ -195,11 +214,19 @@ pub struct AdyenRedirectionResponse {
#[serde(rename_all = "camelCase")]
pub struct AdyenRedirectionAction {
payment_method_type: String,
- url: Url,
- method: services::Method,
+ url: Option<Url>,
+ method: Option<services::Method>,
#[serde(rename = "type")]
- type_of_response: String,
+ type_of_response: ActionType,
data: Option<std::collections::HashMap<String, String>>,
+ payment_data: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ActionType {
+ Redirect,
+ Await,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
@@ -211,26 +238,245 @@ pub struct Amount {
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum AdyenPaymentMethod<'a> {
- AdyenCard(AdyenCard),
- AdyenPaypal(AdyenPaypal),
- Gpay(AdyenGPay),
- ApplePay(AdyenApplePay),
- AfterPay(AdyenPayLaterData),
- AdyenKlarna(AdyenPayLaterData),
- AdyenAffirm(AdyenPayLaterData),
- Eps(BankRedirectionWithIssuer<'a>),
- Ideal(BankRedirectionWithIssuer<'a>),
- Giropay(BankRedirectionPMData),
- Sofort(BankRedirectionPMData),
+ AdyenAffirm(Box<AdyenPayLaterData>),
+ AdyenCard(Box<AdyenCard>),
+ AdyenKlarna(Box<AdyenPayLaterData>),
+ AdyenPaypal(Box<AdyenPaypal>),
+ AfterPay(Box<AdyenPayLaterData>),
+ AliPay(Box<AliPayData>),
+ ApplePay(Box<AdyenApplePay>),
+ BancontactCard(Box<BancontactCardData>),
+ Blik(Box<BlikRedirectionData>),
+ Eps(Box<BankRedirectionWithIssuer<'a>>),
+ Giropay(Box<BankRedirectionPMData>),
+ Gpay(Box<AdyenGPay>),
+ Ideal(Box<BankRedirectionWithIssuer<'a>>),
+ Mbway(Box<MbwayData>),
+ MobilePay(Box<MobilePayData>),
+ OnlineBankingCzechRepublic(Box<OnlineBankingCzechRepublicData>),
+ OnlineBankingFinland(Box<OnlineBankingFinlandData>),
+ OnlineBankingPoland(Box<OnlineBankingPolandData>),
+ OnlineBankingSlovakia(Box<OnlineBankingSlovakiaData>),
+ PayBright(Box<PayBrightData>),
+ Sofort(Box<BankRedirectionPMData>),
+ Trustly(Box<BankRedirectionPMData>),
+ Walley(Box<WalleyData>),
+ WeChatPayWeb(Box<WeChatPayWebData>),
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct WeChatPayWebData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BancontactCardData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+ brand: String,
+ number: Secret<String, pii::CardNumber>,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ holder_name: Secret<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct MobilePayData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MbwayData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+ telephone_number: Secret<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct WalleyData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct PayBrightData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct OnlineBankingFinlandData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+#[derive(Debug, Clone, Serialize)]
+pub struct OnlineBankingCzechRepublicData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+ issuer: OnlineBankingCzechRepublicBanks,
}
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum OnlineBankingCzechRepublicBanks {
+ KB,
+ CS,
+ C,
+}
+
+impl TryFrom<&api_enums::BankNames> for OnlineBankingCzechRepublicBanks {
+ type Error = Error;
+ fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ match bank_name {
+ api::enums::BankNames::KomercniBanka => Ok(Self::KB),
+ api::enums::BankNames::CeskaSporitelna => Ok(Self::CS),
+ api::enums::BankNames::PlatnoscOnlineKartaPlatnicza => Ok(Self::C),
+ _ => Err(errors::ConnectorError::NotSupported {
+ payment_method: String::from("BankRedirect"),
+ connector: "Adyen",
+ payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
+ })?,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct OnlineBankingPolandData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+ issuer: OnlineBankingPolandBanks,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub enum OnlineBankingPolandBanks {
+ #[serde(rename = "154")]
+ BlikPSP,
+ #[serde(rename = "31")]
+ PlaceZIPKO,
+ #[serde(rename = "243")]
+ MBank,
+ #[serde(rename = "112")]
+ PayWithING,
+ #[serde(rename = "20")]
+ SantanderPrzelew24,
+ #[serde(rename = "65")]
+ BankPEKAOSA,
+ #[serde(rename = "85")]
+ BankMillennium,
+ #[serde(rename = "88")]
+ PayWithAliorBank,
+ #[serde(rename = "143")]
+ BankiSpoldzielcze,
+ #[serde(rename = "26")]
+ PayWithInteligo,
+ #[serde(rename = "33")]
+ BNPParibasPoland,
+ #[serde(rename = "144")]
+ BankNowySA,
+ #[serde(rename = "45")]
+ CreditAgricole,
+ #[serde(rename = "99")]
+ PayWithBOS,
+ #[serde(rename = "119")]
+ PayWithCitiHandlowy,
+ #[serde(rename = "131")]
+ PayWithPlusBank,
+ #[serde(rename = "64")]
+ ToyotaBank,
+ #[serde(rename = "153")]
+ VeloBank,
+ #[serde(rename = "141")]
+ ETransferPocztowy24,
+}
+
+impl TryFrom<&api_enums::BankNames> for OnlineBankingPolandBanks {
+ type Error = Error;
+ fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ match bank_name {
+ api_models::enums::BankNames::BlikPSP => Ok(Self::BlikPSP),
+ api_models::enums::BankNames::PlaceZIPKO => Ok(Self::PlaceZIPKO),
+ api_models::enums::BankNames::MBank => Ok(Self::MBank),
+ api_models::enums::BankNames::PayWithING => Ok(Self::PayWithING),
+ api_models::enums::BankNames::SantanderPrzelew24 => Ok(Self::SantanderPrzelew24),
+ api_models::enums::BankNames::BankPEKAOSA => Ok(Self::BankPEKAOSA),
+ api_models::enums::BankNames::BankMillennium => Ok(Self::BankMillennium),
+ api_models::enums::BankNames::PayWithAliorBank => Ok(Self::PayWithAliorBank),
+ api_models::enums::BankNames::BankiSpoldzielcze => Ok(Self::BankiSpoldzielcze),
+ api_models::enums::BankNames::PayWithInteligo => Ok(Self::PayWithInteligo),
+ api_models::enums::BankNames::BNPParibasPoland => Ok(Self::BNPParibasPoland),
+ api_models::enums::BankNames::BankNowySA => Ok(Self::BankNowySA),
+ api_models::enums::BankNames::CreditAgricole => Ok(Self::CreditAgricole),
+ api_models::enums::BankNames::PayWithBOS => Ok(Self::PayWithBOS),
+ api_models::enums::BankNames::PayWithCitiHandlowy => Ok(Self::PayWithCitiHandlowy),
+ api_models::enums::BankNames::PayWithPlusBank => Ok(Self::PayWithPlusBank),
+ api_models::enums::BankNames::ToyotaBank => Ok(Self::ToyotaBank),
+ api_models::enums::BankNames::VeloBank => Ok(Self::VeloBank),
+ api_models::enums::BankNames::ETransferPocztowy24 => Ok(Self::ETransferPocztowy24),
+ _ => Err(errors::ConnectorError::NotSupported {
+ payment_method: String::from("BankRedirect"),
+ connector: "Adyen",
+ payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
+ })?,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OnlineBankingSlovakiaData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+ issuer: OnlineBankingSlovakiaBanks,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum OnlineBankingSlovakiaBanks {
+ Vub,
+ Posto,
+ Sporo,
+ Tatra,
+ Viamo,
+}
+
+impl TryFrom<&api_enums::BankNames> for OnlineBankingSlovakiaBanks {
+ type Error = Error;
+ fn try_from(bank_name: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ match bank_name {
+ api::enums::BankNames::EPlatbyVUB => Ok(Self::Vub),
+ api::enums::BankNames::PostovaBanka => Ok(Self::Posto),
+ api::enums::BankNames::SporoPay => Ok(Self::Sporo),
+ api::enums::BankNames::TatraPay => Ok(Self::Tatra),
+ api::enums::BankNames::Viamo => Ok(Self::Viamo),
+ _ => Err(errors::ConnectorError::NotSupported {
+ payment_method: String::from("BankRedirect"),
+ connector: "Adyen",
+ payment_experience: api_enums::PaymentExperience::RedirectToUrl.to_string(),
+ })?,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BlikRedirectionData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+ blik_code: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct BankRedirectionPMData {
#[serde(rename = "type")]
payment_type: PaymentType,
}
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct BankRedirectionWithIssuer<'a> {
#[serde(rename = "type")]
payment_type: PaymentType,
@@ -270,12 +516,17 @@ pub enum CancelStatus {
Processing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
pub struct AdyenPaypal {
#[serde(rename = "type")]
payment_type: PaymentType,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AliPayData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdyenGPay {
#[serde(rename = "type")]
@@ -326,24 +577,41 @@ pub struct AdyenAuthType {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentType {
- Scheme,
- Googlepay,
- Applepay,
- Paypal,
- Klarna,
Affirm,
Afterpaytouch,
+ Alipay,
+ Applepay,
+ Blik,
Eps,
- Ideal,
Giropay,
+ Googlepay,
+ Ideal,
+ Klarna,
+ Mbway,
+ MobilePay,
+ #[serde(rename = "onlineBanking_CZ")]
+ OnlineBankingCzechRepublic,
+ #[serde(rename = "ebanking_FI")]
+ OnlineBankingFinland,
+ #[serde(rename = "onlineBanking_PL")]
+ OnlineBankingPoland,
+ #[serde(rename = "onlineBanking_SK")]
+ OnlineBankingSlovakia,
+ PayBright,
+ Paypal,
+ Scheme,
#[serde(rename = "directEbanking")]
Sofort,
+ Trustly,
+ Walley,
+ #[serde(rename = "wechatpayWeb")]
+ WeChatPayWeb,
}
pub struct AdyenTestBankNames<'a>(&'a str);
impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> {
Ok(match bank {
api_models::enums::BankNames::AbnAmro => Self("1121"),
@@ -405,7 +673,7 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
}
impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
@@ -418,27 +686,27 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType {
}
}
-// Payment Request Transform
impl<'a> TryFrom<&types::PaymentsAuthorizeRouterData> for AdyenPaymentRequest<'a> {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- match item.payment_method {
- storage_models::enums::PaymentMethod::Card => get_card_specific_payment_data(item),
- storage_models::enums::PaymentMethod::PayLater => {
- get_paylater_specific_payment_data(item)
+ match item.request.payment_method_data {
+ api_models::payments::PaymentMethodData::Card(ref card) => {
+ AdyenPaymentRequest::try_from((item, card))
+ }
+ api_models::payments::PaymentMethodData::Wallet(ref wallet) => {
+ AdyenPaymentRequest::try_from((item, wallet))
}
- storage_models::enums::PaymentMethod::Wallet => get_wallet_specific_payment_data(item),
- storage_models::enums::PaymentMethod::BankRedirect => {
- get_bank_redirect_specific_payment_data(item)
+ api_models::payments::PaymentMethodData::PayLater(ref pay_later) => {
+ AdyenPaymentRequest::try_from((item, pay_later))
}
- storage_models::enums::PaymentMethod::Crypto => {
- Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{:?}", item.payment_method),
- connector: "Adyen",
- payment_experience: api_models::enums::PaymentExperience::RedirectToUrl
- .to_string(),
- })?
+ api_models::payments::PaymentMethodData::BankRedirect(ref bank_redirect) => {
+ AdyenPaymentRequest::try_from((item, bank_redirect))
}
+ _ => Err(errors::ConnectorError::NotSupported {
+ payment_method: format!("{:?}", item.request.payment_method_type),
+ connector: "Adyen",
+ payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(),
+ })?,
}
}
}
@@ -464,7 +732,9 @@ fn get_recurring_processing_model(
}
fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<AdyenBrowserInfo> {
- if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) {
+ if item.auth_type == storage_enums::AuthenticationType::ThreeDs
+ || item.payment_method == storage_enums::PaymentMethod::BankRedirect
+ {
item.request
.browser_info
.as_ref()
@@ -517,13 +787,13 @@ fn get_line_items(item: &types::PaymentsAuthorizeRouterData) -> Vec<LineItem> {
let order_details = item.request.order_details.as_ref();
let line_item = LineItem {
amount_including_tax: Some(item.request.amount),
- amount_excluding_tax: None,
+ amount_excluding_tax: Some(item.request.amount),
description: order_details.map(|details| details.product_name.clone()),
// We support only one product details in payment request as of now, therefore hard coded the id.
// If we begin to support multiple product details in future then this logic should be made to create ID dynamically
id: Some(String::from("Items #1")),
tax_amount: None,
- quantity: order_details.map(|details| details.quantity),
+ quantity: Some(order_details.map_or(1, |details| details.quantity)),
};
vec![line_item]
}
@@ -563,27 +833,30 @@ fn get_country_code(item: &types::PaymentsAuthorizeRouterData) -> Option<api_enu
.and_then(|billing| billing.address.as_ref().and_then(|address| address.country))
}
-fn get_payment_method_data<'a>(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<AdyenPaymentMethod<'a>, error_stack::Report<errors::ConnectorError>> {
- match item.request.payment_method_data {
- api::PaymentMethodData::Card(ref card) => {
- let adyen_card = AdyenCard {
- payment_type: PaymentType::Scheme,
- number: card.card_number.clone(),
- expiry_month: card.card_exp_month.clone(),
- expiry_year: card.card_exp_year.clone(),
- cvc: Some(card.card_cvc.clone()),
- };
- Ok(AdyenPaymentMethod::AdyenCard(adyen_card))
- }
- api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
+impl<'a> TryFrom<&api::Card> for AdyenPaymentMethod<'a> {
+ type Error = Error;
+ fn try_from(card: &api::Card) -> Result<Self, Self::Error> {
+ let adyen_card = AdyenCard {
+ payment_type: PaymentType::Scheme,
+ number: card.card_number.clone(),
+ expiry_month: card.card_exp_month.clone(),
+ expiry_year: card.card_exp_year.clone(),
+ cvc: Some(card.card_cvc.clone()),
+ };
+ Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card)))
+ }
+}
+
+impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> {
+ type Error = Error;
+ fn try_from(wallet_data: &api::WalletData) -> Result<Self, Self::Error> {
+ match wallet_data {
api_models::payments::WalletData::GooglePay(data) => {
let gpay_data = AdyenGPay {
payment_type: PaymentType::Googlepay,
google_pay_token: data.tokenization_data.token.to_owned(),
};
- Ok(AdyenPaymentMethod::Gpay(gpay_data))
+ Ok(AdyenPaymentMethod::Gpay(Box::new(gpay_data)))
}
api_models::payments::WalletData::ApplePay(data) => {
let apple_pay_data = AdyenApplePay {
@@ -591,106 +864,244 @@ fn get_payment_method_data<'a>(
apple_pay_token: data.payment_data.to_string(),
};
- Ok(AdyenPaymentMethod::ApplePay(apple_pay_data))
- }
- api_models::payments::WalletData::PaypalSdk(_) => {
- Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
+ Ok(AdyenPaymentMethod::ApplePay(Box::new(apple_pay_data)))
}
api_models::payments::WalletData::PaypalRedirect(_) => {
let wallet = AdyenPaypal {
payment_type: PaymentType::Paypal,
};
- Ok(AdyenPaymentMethod::AdyenPaypal(wallet))
+ Ok(AdyenPaymentMethod::AdyenPaypal(Box::new(wallet)))
}
- },
- api_models::payments::PaymentMethodData::PayLater(ref pay_later_data) => {
- match pay_later_data {
- api_models::payments::PayLaterData::KlarnaRedirect { .. } => {
- let klarna = AdyenPayLaterData {
- payment_type: PaymentType::Klarna,
- };
- Ok(AdyenPaymentMethod::AdyenKlarna(klarna))
- }
- api_models::payments::PayLaterData::AffirmRedirect { .. } => {
- Ok(AdyenPaymentMethod::AdyenAffirm(AdyenPayLaterData {
- payment_type: PaymentType::Affirm,
- }))
- }
- api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
- Ok(AdyenPaymentMethod::AfterPay(AdyenPayLaterData {
- payment_type: PaymentType::Afterpaytouch,
- }))
- }
- _ => Err(
- errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(),
- ),
+ api_models::payments::WalletData::AliPay(_) => {
+ let alipay_data = AliPayData {
+ payment_type: PaymentType::Alipay,
+ };
+ Ok(AdyenPaymentMethod::AliPay(Box::new(alipay_data)))
}
+ api_models::payments::WalletData::MbWay(data) => {
+ let mbway_data = MbwayData {
+ payment_type: PaymentType::Mbway,
+ telephone_number: data.telephone_number.clone(),
+ };
+ Ok(AdyenPaymentMethod::Mbway(Box::new(mbway_data)))
+ }
+ api_models::payments::WalletData::MobilePay(_) => {
+ let data = MobilePayData {
+ payment_type: PaymentType::MobilePay,
+ };
+ Ok(AdyenPaymentMethod::MobilePay(Box::new(data)))
+ }
+ api_models::payments::WalletData::WeChatPayRedirect(_) => {
+ let data = WeChatPayWebData {
+ payment_type: PaymentType::WeChatPayWeb,
+ };
+ Ok(AdyenPaymentMethod::WeChatPayWeb(Box::new(data)))
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
- api_models::payments::PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
- match bank_redirect_data {
- api_models::payments::BankRedirectData::Eps { bank_name, .. } => {
- Ok(AdyenPaymentMethod::Eps(BankRedirectionWithIssuer {
- payment_type: PaymentType::Eps,
- issuer: AdyenTestBankNames::try_from(bank_name)?.0,
- }))
- }
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
- Ok(AdyenPaymentMethod::Ideal(BankRedirectionWithIssuer {
- payment_type: PaymentType::Ideal,
- issuer: AdyenTestBankNames::try_from(bank_name)?.0,
- }))
- }
-
- api_models::payments::BankRedirectData::Giropay { .. } => {
- Ok(AdyenPaymentMethod::Giropay(BankRedirectionPMData {
- payment_type: PaymentType::Giropay,
- }))
- }
- api_models::payments::BankRedirectData::Sofort { .. } => {
- Ok(AdyenPaymentMethod::Sofort(BankRedirectionPMData {
- payment_type: PaymentType::Sofort,
- }))
- }
+ }
+}
+
+impl<'a> TryFrom<&api::PayLaterData> for AdyenPaymentMethod<'a> {
+ type Error = Error;
+ fn try_from(pay_later_data: &api::PayLaterData) -> Result<Self, Self::Error> {
+ match pay_later_data {
+ api_models::payments::PayLaterData::KlarnaRedirect { .. } => {
+ let klarna = AdyenPayLaterData {
+ payment_type: PaymentType::Klarna,
+ };
+ Ok(AdyenPaymentMethod::AdyenKlarna(Box::new(klarna)))
+ }
+ api_models::payments::PayLaterData::AffirmRedirect { .. } => Ok(
+ AdyenPaymentMethod::AdyenAffirm(Box::new(AdyenPayLaterData {
+ payment_type: PaymentType::Affirm,
+ })),
+ ),
+ api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
+ Ok(AdyenPaymentMethod::AfterPay(Box::new(AdyenPayLaterData {
+ payment_type: PaymentType::Afterpaytouch,
+ })))
+ }
+ api_models::payments::PayLaterData::PayBright { .. } => {
+ Ok(AdyenPaymentMethod::PayBright(Box::new(PayBrightData {
+ payment_type: PaymentType::PayBright,
+ })))
+ }
+ api_models::payments::PayLaterData::Walley { .. } => {
+ Ok(AdyenPaymentMethod::Walley(Box::new(WalleyData {
+ payment_type: PaymentType::Walley,
+ })))
}
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
- api::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotSupported {
- payment_method: format!("{:?}", item.payment_method),
- connector: "Adyen",
- payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(),
- })?,
}
}
-fn get_card_specific_payment_data<'a>(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<AdyenPaymentRequest<'a>, error_stack::Report<errors::ConnectorError>> {
- let amount = get_amount_data(item);
- let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
- let shopper_interaction = AdyenShopperInteraction::from(item);
- let recurring_processing_model = get_recurring_processing_model(item);
- let browser_info = get_browser_info(item);
- let additional_data = get_additional_data(item);
- let return_url = item.request.get_return_url()?;
- let payment_method = get_payment_method_data(item)?;
- Ok(AdyenPaymentRequest {
- amount,
- merchant_account: auth_type.merchant_account,
- payment_method,
- reference: item.payment_id.to_string(),
- return_url,
- shopper_interaction,
- recurring_processing_model,
- browser_info,
- additional_data,
- telephone_number: None,
- shopper_name: None,
- shopper_email: None,
- shopper_locale: None,
- billing_address: None,
- delivery_address: None,
- country_code: None,
- line_items: None,
- })
+impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod<'a> {
+ type Error = Error;
+ fn try_from(
+ bank_redirect_data: &api_models::payments::BankRedirectData,
+ ) -> Result<Self, Self::Error> {
+ match bank_redirect_data {
+ api_models::payments::BankRedirectData::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name,
+ } => Ok(AdyenPaymentMethod::BancontactCard(Box::new(
+ BancontactCardData {
+ payment_type: PaymentType::Scheme,
+ brand: "bcmc".to_string(),
+ number: card_number.clone(),
+ expiry_month: card_exp_month.clone(),
+ expiry_year: card_exp_year.clone(),
+ holder_name: card_holder_name.clone(),
+ },
+ ))),
+ api_models::payments::BankRedirectData::Blik { blik_code } => {
+ Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData {
+ payment_type: PaymentType::Blik,
+ blik_code: blik_code.to_string(),
+ })))
+ }
+ api_models::payments::BankRedirectData::Eps { bank_name, .. } => Ok(
+ AdyenPaymentMethod::Eps(Box::new(BankRedirectionWithIssuer {
+ payment_type: PaymentType::Eps,
+ issuer: AdyenTestBankNames::try_from(bank_name)?.0,
+ })),
+ ),
+ api_models::payments::BankRedirectData::Giropay { .. } => Ok(
+ AdyenPaymentMethod::Giropay(Box::new(BankRedirectionPMData {
+ payment_type: PaymentType::Giropay,
+ })),
+ ),
+ api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok(
+ AdyenPaymentMethod::Ideal(Box::new(BankRedirectionWithIssuer {
+ payment_type: PaymentType::Ideal,
+ issuer: AdyenTestBankNames::try_from(bank_name)?.0,
+ })),
+ ),
+ api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
+ Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new(
+ OnlineBankingCzechRepublicData {
+ payment_type: PaymentType::OnlineBankingCzechRepublic,
+ issuer: OnlineBankingCzechRepublicBanks::try_from(issuer)?,
+ },
+ )))
+ }
+ api_models::payments::BankRedirectData::OnlineBankingFinland { .. } => Ok(
+ AdyenPaymentMethod::OnlineBankingFinland(Box::new(OnlineBankingFinlandData {
+ payment_type: PaymentType::OnlineBankingFinland,
+ })),
+ ),
+ api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => Ok(
+ AdyenPaymentMethod::OnlineBankingPoland(Box::new(OnlineBankingPolandData {
+ payment_type: PaymentType::OnlineBankingPoland,
+ issuer: OnlineBankingPolandBanks::try_from(issuer)?,
+ })),
+ ),
+ api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => Ok(
+ AdyenPaymentMethod::OnlineBankingSlovakia(Box::new(OnlineBankingSlovakiaData {
+ payment_type: PaymentType::OnlineBankingSlovakia,
+ issuer: OnlineBankingSlovakiaBanks::try_from(issuer)?,
+ })),
+ ),
+ api_models::payments::BankRedirectData::Sofort { .. } => Ok(
+ AdyenPaymentMethod::Sofort(Box::new(BankRedirectionPMData {
+ payment_type: PaymentType::Sofort,
+ })),
+ ),
+ api_models::payments::BankRedirectData::Trustly {} => Ok(AdyenPaymentMethod::Trustly(
+ Box::new(BankRedirectionPMData {
+ payment_type: PaymentType::Trustly,
+ }),
+ )),
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
+ }
+ }
+}
+
+impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AdyenPaymentRequest<'a> {
+ type Error = Error;
+ fn try_from(
+ value: (&types::PaymentsAuthorizeRouterData, &api::Card),
+ ) -> Result<Self, Self::Error> {
+ let (item, card_data) = value;
+ let amount = get_amount_data(item);
+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
+ let shopper_interaction = AdyenShopperInteraction::from(item);
+ let recurring_processing_model = get_recurring_processing_model(item);
+ let browser_info = get_browser_info(item);
+ let additional_data = get_additional_data(item);
+ let return_url = item.request.get_return_url()?;
+ let payment_method = AdyenPaymentMethod::try_from(card_data)?;
+ Ok(AdyenPaymentRequest {
+ amount,
+ merchant_account: auth_type.merchant_account,
+ payment_method,
+ reference: item.payment_id.to_string(),
+ return_url,
+ shopper_interaction,
+ recurring_processing_model,
+ browser_info,
+ additional_data,
+ telephone_number: None,
+ shopper_name: None,
+ shopper_email: None,
+ shopper_locale: None,
+ billing_address: None,
+ delivery_address: None,
+ country_code: None,
+ line_items: None,
+ })
+ }
+}
+
+impl<'a>
+ TryFrom<(
+ &types::PaymentsAuthorizeRouterData,
+ &api_models::payments::BankRedirectData,
+ )> for AdyenPaymentRequest<'a>
+{
+ type Error = Error;
+ fn try_from(
+ value: (
+ &types::PaymentsAuthorizeRouterData,
+ &api_models::payments::BankRedirectData,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (item, bank_redirect_data) = value;
+ let amount = get_amount_data(item);
+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
+ let shopper_interaction = AdyenShopperInteraction::from(item);
+ let recurring_processing_model = get_recurring_processing_model(item);
+ let browser_info = get_browser_info(item);
+ let additional_data = get_additional_data(item);
+ let return_url = item.request.get_return_url()?;
+ let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?;
+ let (shopper_locale, country) = get_sofort_extra_details(item);
+ let line_items = Some(get_line_items(item));
+
+ Ok(AdyenPaymentRequest {
+ amount,
+ merchant_account: auth_type.merchant_account,
+ payment_method,
+ reference: item.payment_id.to_string(),
+ return_url,
+ shopper_interaction,
+ recurring_processing_model,
+ browser_info,
+ additional_data,
+ telephone_number: None,
+ shopper_name: None,
+ shopper_email: item.request.email.clone(),
+ shopper_locale,
+ billing_address: None,
+ delivery_address: None,
+ country_code: country,
+ line_items,
+ })
+ }
}
fn get_sofort_extra_details(
@@ -715,113 +1126,92 @@ fn get_sofort_extra_details(
_ => (None, None),
}
}
-fn get_bank_redirect_specific_payment_data<'a>(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<AdyenPaymentRequest<'a>, error_stack::Report<errors::ConnectorError>> {
- let amount = get_amount_data(item);
- let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
- let shopper_interaction = AdyenShopperInteraction::from(item);
- let recurring_processing_model = get_recurring_processing_model(item);
- let browser_info = get_browser_info(item);
- let additional_data = get_additional_data(item);
- let return_url = item.request.get_return_url()?;
- let payment_method = get_payment_method_data(item)?;
- let (shopper_locale, country) = get_sofort_extra_details(item);
-
- Ok(AdyenPaymentRequest {
- amount,
- merchant_account: auth_type.merchant_account,
- payment_method,
- reference: item.payment_id.to_string(),
- return_url,
- shopper_interaction,
- recurring_processing_model,
- browser_info,
- additional_data,
- telephone_number: None,
- shopper_name: None,
- shopper_email: None,
- shopper_locale,
- billing_address: None,
- delivery_address: None,
- country_code: country,
- line_items: None,
- })
-}
-fn get_wallet_specific_payment_data<'a>(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<AdyenPaymentRequest<'a>, error_stack::Report<errors::ConnectorError>> {
- let amount = get_amount_data(item);
- let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
- let browser_info = get_browser_info(item);
- let additional_data = get_additional_data(item);
- let payment_method = get_payment_method_data(item)?;
- let shopper_interaction = AdyenShopperInteraction::from(item);
- let recurring_processing_model = get_recurring_processing_model(item);
- let return_url = item.request.get_return_url()?;
- Ok(AdyenPaymentRequest {
- amount,
- merchant_account: auth_type.merchant_account,
- payment_method,
- reference: item.payment_id.to_string(),
- return_url,
- shopper_interaction,
- recurring_processing_model,
- browser_info,
- additional_data,
- telephone_number: None,
- shopper_name: None,
- shopper_email: None,
- shopper_locale: None,
- billing_address: None,
- delivery_address: None,
- country_code: None,
- line_items: None,
- })
+impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::WalletData)>
+ for AdyenPaymentRequest<'a>
+{
+ type Error = Error;
+ fn try_from(
+ value: (&types::PaymentsAuthorizeRouterData, &api::WalletData),
+ ) -> Result<Self, Self::Error> {
+ let (item, wallet_data) = value;
+ let amount = get_amount_data(item);
+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
+ let browser_info = get_browser_info(item);
+ let additional_data = get_additional_data(item);
+ let payment_method = AdyenPaymentMethod::try_from(wallet_data)?;
+ let shopper_interaction = AdyenShopperInteraction::from(item);
+ let recurring_processing_model = get_recurring_processing_model(item);
+ let return_url = item.request.get_return_url()?;
+ Ok(AdyenPaymentRequest {
+ amount,
+ merchant_account: auth_type.merchant_account,
+ payment_method,
+ reference: item.payment_id.to_string(),
+ return_url,
+ shopper_interaction,
+ recurring_processing_model,
+ browser_info,
+ additional_data,
+ telephone_number: None,
+ shopper_name: None,
+ shopper_email: None,
+ shopper_locale: None,
+ billing_address: None,
+ delivery_address: None,
+ country_code: None,
+ line_items: None,
+ })
+ }
}
-fn get_paylater_specific_payment_data<'a>(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<AdyenPaymentRequest<'a>, error_stack::Report<errors::ConnectorError>> {
- let amount = get_amount_data(item);
- let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
- let browser_info = get_browser_info(item);
- let additional_data = get_additional_data(item);
- let payment_method = get_payment_method_data(item)?;
- let shopper_interaction = AdyenShopperInteraction::from(item);
- let recurring_processing_model = get_recurring_processing_model(item);
- let return_url = item.request.get_return_url()?;
- let shopper_name = get_shopper_name(item);
- let shopper_email = item.request.email.clone();
- let billing_address = get_address_info(item.address.billing.as_ref());
- let delivery_address = get_address_info(item.address.shipping.as_ref());
- let country_code = get_country_code(item);
- let line_items = Some(get_line_items(item));
- let telephone_number = get_telephone_number(item);
- Ok(AdyenPaymentRequest {
- amount,
- merchant_account: auth_type.merchant_account,
- payment_method,
- reference: item.payment_id.to_string(),
- return_url,
- shopper_interaction,
- recurring_processing_model,
- browser_info,
- additional_data,
- telephone_number,
- shopper_name,
- shopper_email,
- shopper_locale: None,
- billing_address,
- delivery_address,
- country_code,
- line_items,
- })
+impl<'a> TryFrom<(&types::PaymentsAuthorizeRouterData, &api::PayLaterData)>
+ for AdyenPaymentRequest<'a>
+{
+ type Error = Error;
+ fn try_from(
+ value: (&types::PaymentsAuthorizeRouterData, &api::PayLaterData),
+ ) -> Result<Self, Self::Error> {
+ let (item, paylater_data) = value;
+ let amount = get_amount_data(item);
+ let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
+ let browser_info = get_browser_info(item);
+ let additional_data = get_additional_data(item);
+ let payment_method = AdyenPaymentMethod::try_from(paylater_data)?;
+ let shopper_interaction = AdyenShopperInteraction::from(item);
+ let recurring_processing_model = get_recurring_processing_model(item);
+ let return_url = item.request.get_return_url()?;
+ let shopper_name = get_shopper_name(item);
+ let shopper_email = item.request.email.clone();
+ let billing_address = get_address_info(item.address.billing.as_ref());
+ let delivery_address = get_address_info(item.address.shipping.as_ref());
+ let country_code = get_country_code(item);
+ let line_items = Some(get_line_items(item));
+ let telephone_number = get_telephone_number(item);
+ Ok(AdyenPaymentRequest {
+ amount,
+ merchant_account: auth_type.merchant_account,
+ payment_method,
+ reference: item.payment_id.to_string(),
+ return_url,
+ shopper_interaction,
+ recurring_processing_model,
+ browser_info,
+ additional_data,
+ telephone_number,
+ shopper_name,
+ shopper_email,
+ shopper_locale: None,
+ billing_address,
+ delivery_address,
+ country_code,
+ line_items,
+ })
+ }
}
impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
@@ -843,7 +1233,7 @@ impl From<CancelStatus> for storage_enums::AttemptStatus {
impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>>
for types::PaymentsCancelRouterData
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::PaymentsCancelResponseRouterData<AdyenCancelResponse>,
) -> Result<Self, Self::Error> {
@@ -872,17 +1262,8 @@ pub fn get_adyen_response(
),
errors::ConnectorError,
> {
- let status = match response.result_code {
- AdyenStatus::Authorised => {
- if is_capture_manual {
- storage_enums::AttemptStatus::Authorized
- } else {
- storage_enums::AttemptStatus::Charged
- }
- }
- AdyenStatus::Refused | AdyenStatus::Cancelled => storage_enums::AttemptStatus::Failure,
- _ => storage_enums::AttemptStatus::Pending,
- };
+ let status =
+ storage_enums::AttemptStatus::foreign_from((is_capture_manual, response.result_code));
let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() {
Some(types::ErrorResponse {
code: response
@@ -909,6 +1290,7 @@ pub fn get_adyen_response(
pub fn get_redirection_response(
response: AdyenRedirectionResponse,
+ is_manual_capture: bool,
status_code: u16,
) -> errors::CustomResult<
(
@@ -918,8 +1300,8 @@ pub fn get_redirection_response(
),
errors::ConnectorError,
> {
- let status = response.result_code.into();
-
+ let status =
+ storage_enums::AttemptStatus::foreign_from((is_manual_capture, response.result_code));
let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() {
Some(types::ErrorResponse {
code: response
@@ -935,26 +1317,24 @@ pub fn get_redirection_response(
None
};
- let form_fields = response.action.data.unwrap_or_else(|| {
- std::collections::HashMap::from_iter(
- response
- .action
- .url
- .query_pairs()
- .map(|(key, value)| (key.to_string(), value.to_string())),
- )
+ let redirection_data = response.action.url.map(|url| {
+ let form_fields = response.action.data.unwrap_or_else(|| {
+ std::collections::HashMap::from_iter(
+ url.query_pairs()
+ .map(|(key, value)| (key.to_string(), value.to_string())),
+ )
+ });
+ services::RedirectForm {
+ endpoint: url.to_string(),
+ method: response.action.method.unwrap_or(services::Method::Get),
+ form_fields,
+ }
});
- let redirection_data = services::RedirectForm {
- endpoint: response.action.url.to_string(),
- method: response.action.method,
- form_fields,
- };
-
// We don't get connector transaction id for redirections in Adyen.
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(redirection_data),
+ redirection_data,
mandate_reference: None,
connector_metadata: None,
};
@@ -967,7 +1347,7 @@ impl<F, Req>
bool,
)> for types::RouterData<F, Req, types::PaymentsResponseData>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
items: (
types::ResponseRouterData<F, AdyenPaymentResponse, Req, types::PaymentsResponseData>,
@@ -981,7 +1361,7 @@ impl<F, Req>
get_adyen_response(response, is_manual_capture, item.http_code)?
}
AdyenPaymentResponse::AdyenRedirectResponse(response) => {
- get_redirection_response(response, item.http_code)?
+ get_redirection_response(response, is_manual_capture, item.http_code)?
}
};
@@ -1001,7 +1381,7 @@ pub struct AdyenCaptureRequest {
}
impl TryFrom<&types::PaymentsCaptureRouterData> for AdyenCaptureRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
@@ -1029,7 +1409,7 @@ pub struct AdyenCaptureResponse {
impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
for types::PaymentsCaptureRouterData
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>,
) -> Result<Self, Self::Error> {
@@ -1089,7 +1469,7 @@ impl From<AdyenPaymentStatus> for enums::Status {
*/
// Refund Request Transform
impl<F> TryFrom<&types::RefundsRouterData<F>> for AdyenRefundRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
@@ -1108,7 +1488,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for AdyenRefundRequest {
impl<F> TryFrom<types::RefundsResponseRouterData<F, AdyenRefundResponse>>
for types::RefundsRouterData<F>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::RefundsResponseRouterData<F, AdyenRefundResponse>,
) -> Result<Self, Self::Error> {
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index a22d17cb377..d76b09b5ced 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -19,13 +19,15 @@ use crate::{
types::{self, api, storage::enums, ErrorResponse},
};
+type Error = error_stack::Report<errors::ConnectorError>;
+
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalPayMeta {
account_name: String,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let metadata: GlobalPayMeta =
utils::to_connector_meta_from_secret(item.connector_meta_data.clone())?;
@@ -84,7 +86,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest {
}
impl TryFrom<&types::PaymentsCaptureRouterData> for requests::GlobalpayCaptureRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(value: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(value.request.amount_to_capture.to_string()),
@@ -93,7 +95,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for requests::GlobalpayCaptureRe
}
impl TryFrom<&types::PaymentsCancelRouterData> for requests::GlobalpayCancelRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(value: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
amount: value.request.amount.map(|amount| amount.to_string()),
@@ -107,7 +109,7 @@ pub struct GlobalpayAuthType {
}
impl TryFrom<&types::ConnectorAuthType> for GlobalpayAuthType {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
@@ -131,7 +133,7 @@ impl TryFrom<GlobalpayRefreshTokenResponse> for types::AccessToken {
}
impl TryFrom<&types::RefreshTokenRouterData> for GlobalpayRefreshTokenRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let globalpay_auth = GlobalpayAuthType::try_from(&item.connector_auth_type)
@@ -220,7 +222,7 @@ impl<F, T>
TryFrom<types::ResponseRouterData<F, GlobalpayPaymentsResponse, T, types::PaymentsResponseData>>
for types::RouterData<F, T, types::PaymentsResponseData>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::ResponseRouterData<
F,
@@ -276,7 +278,7 @@ impl<F, T>
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for requests::GlobalpayRefundRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.request.refund_amount.to_string(),
@@ -287,7 +289,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for requests::GlobalpayRefundReque
impl TryFrom<types::RefundsResponseRouterData<api::Execute, GlobalpayPaymentsResponse>>
for types::RefundExecuteRouterData
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::RefundsResponseRouterData<api::Execute, GlobalpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
@@ -304,7 +306,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, GlobalpayPaymentsRes
impl TryFrom<types::RefundsResponseRouterData<api::RSync, GlobalpayPaymentsResponse>>
for types::RefundsRouterData<api::RSync>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::RefundsResponseRouterData<api::RSync, GlobalpayPaymentsResponse>,
) -> Result<Self, Self::Error> {
@@ -328,7 +330,7 @@ pub struct GlobalpayErrorResponse {
fn get_payment_method_data(
item: &types::PaymentsAuthorizeRouterData,
brand_reference: Option<String>,
-) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {
+) -> Result<PaymentMethodData, Error> {
match &item.request.payment_method_data {
api::PaymentMethodData::Card(ccard) => Ok(PaymentMethodData::Card(requests::Card {
number: ccard.card_number.clone(),
@@ -348,7 +350,7 @@ fn get_payment_method_data(
})),
api::PaymentMethodData::Wallet(wallet_data) => get_wallet_data(wallet_data),
api::PaymentMethodData::BankRedirect(bank_redirect) => {
- get_bank_redirect_data(bank_redirect)
+ PaymentMethodData::try_from(bank_redirect)
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment methods".to_string(),
@@ -366,9 +368,7 @@ fn get_return_url(item: &types::PaymentsAuthorizeRouterData) -> Option<String> {
}
type MandateDetails = (Option<Initiator>, Option<StoredCredential>, Option<String>);
-fn get_mandate_details(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<MandateDetails, error_stack::Report<errors::ConnectorError>> {
+fn get_mandate_details(item: &types::PaymentsAuthorizeRouterData) -> Result<MandateDetails, Error> {
Ok(if item.request.is_mandate_payment() {
let connector_mandate_id = item
.request
@@ -396,7 +396,7 @@ fn get_mandate_details(
fn get_wallet_data(
wallet_data: &api_models::payments::WalletData,
-) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {
+) -> Result<PaymentMethodData, Error> {
match wallet_data {
api_models::payments::WalletData::PaypalRedirect(_) => {
Ok(PaymentMethodData::Apm(requests::Apm {
@@ -410,34 +410,33 @@ fn get_wallet_data(
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
- "Payment methods".to_string(),
+ "Payment method".to_string(),
))?,
}
}
-fn get_bank_redirect_data(
- bank_redirect: &api_models::payments::BankRedirectData,
-) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {
- match bank_redirect {
- api_models::payments::BankRedirectData::Eps { .. } => {
- Ok(PaymentMethodData::Apm(requests::Apm {
+impl TryFrom<&api_models::payments::BankRedirectData> for PaymentMethodData {
+ type Error = Error;
+ fn try_from(value: &api_models::payments::BankRedirectData) -> Result<Self, Self::Error> {
+ match value {
+ api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Eps),
- }))
- }
- api_models::payments::BankRedirectData::Giropay { .. } => {
- Ok(PaymentMethodData::Apm(requests::Apm {
- provider: Some(ApmProvider::Giropay),
- }))
- }
- api_models::payments::BankRedirectData::Ideal { .. } => {
- Ok(PaymentMethodData::Apm(requests::Apm {
+ })),
+ api_models::payments::BankRedirectData::Giropay { .. } => {
+ Ok(Self::Apm(requests::Apm {
+ provider: Some(ApmProvider::Giropay),
+ }))
+ }
+ api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Ideal),
- }))
- }
- api_models::payments::BankRedirectData::Sofort { .. } => {
- Ok(PaymentMethodData::Apm(requests::Apm {
+ })),
+ api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Apm(requests::Apm {
provider: Some(ApmProvider::Sofort),
- }))
+ })),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "Payment method".to_string(),
+ ))
+ .into_report(),
}
}
}
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index 464994023ac..feafe661092 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -98,7 +98,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MolliePaymentsRequest {
let payment_method_data = match item.request.capture_method.unwrap_or_default() {
enums::CaptureMethod::Automatic => match item.request.payment_method_data {
api_models::payments::PaymentMethodData::BankRedirect(ref redirect_data) => {
- get_payment_method_for_bank_redirect(item, redirect_data)
+ PaymentMethodData::try_from(redirect_data)
}
api_models::payments::PaymentMethodData::Wallet(ref wallet_data) => {
get_payment_method_for_wallet(item, wallet_data)
@@ -135,22 +135,22 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MolliePaymentsRequest {
}
}
-fn get_payment_method_for_bank_redirect(
- _item: &types::PaymentsAuthorizeRouterData,
- redirect_data: &api_models::payments::BankRedirectData,
-) -> Result<PaymentMethodData, Error> {
- let payment_method_data = match redirect_data {
- api_models::payments::BankRedirectData::Eps { .. } => PaymentMethodData::Eps,
- api_models::payments::BankRedirectData::Giropay { .. } => PaymentMethodData::Giropay,
- api_models::payments::BankRedirectData::Ideal { .. } => {
- PaymentMethodData::Ideal(Box::new(IdealMethodData {
- // To do if possible this should be from the payment request
- issuer: None,
- }))
+impl TryFrom<&api_models::payments::BankRedirectData> for PaymentMethodData {
+ type Error = Error;
+ fn try_from(value: &api_models::payments::BankRedirectData) -> Result<Self, Self::Error> {
+ match value {
+ api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ api_models::payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ api_models::payments::BankRedirectData::Ideal { .. } => {
+ Ok(Self::Ideal(Box::new(IdealMethodData {
+ // To do if possible this should be from the payment request
+ issuer: None,
+ })))
+ }
+ api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
- api_models::payments::BankRedirectData::Sofort { .. } => PaymentMethodData::Sofort,
- };
- Ok(payment_method_data)
+ }
}
fn get_payment_method_for_wallet(
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index b0955ac3f8e..a77ada4bdf0 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -198,7 +198,7 @@ fn get_bank_redirect_request<T>(
redirect_data: &payments::BankRedirectData,
) -> Result<Shift4PaymentsRequest, Error> {
let submit_for_settlement = item.request.is_auto_capture()?;
- let method_type = PaymentMethodType::from(redirect_data);
+ let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = get_billing(item)?;
let payment_method = Some(PaymentMethod {
method_type,
@@ -218,13 +218,15 @@ fn get_bank_redirect_request<T>(
)))
}
-impl From<&payments::BankRedirectData> for PaymentMethodType {
- fn from(value: &payments::BankRedirectData) -> Self {
+impl TryFrom<&payments::BankRedirectData> for PaymentMethodType {
+ type Error = Error;
+ fn try_from(value: &payments::BankRedirectData) -> Result<Self, Self::Error> {
match value {
- payments::BankRedirectData::Eps { .. } => Self::Eps,
- payments::BankRedirectData::Giropay { .. } => Self::Giropay,
- payments::BankRedirectData::Ideal { .. } => Self::Ideal,
- payments::BankRedirectData::Sofort { .. } => Self::Sofort,
+ payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ payments::BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
+ payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index a28c6f2bcc1..f039321070a 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -18,6 +18,8 @@ use crate::{
types::{self, api, storage::enums, BrowserInformation},
};
+type Error = error_stack::Report<errors::ConnectorError>;
+
pub struct TrustpayAuthType {
pub(super) api_key: String,
pub(super) project_id: String,
@@ -25,7 +27,7 @@ pub struct TrustpayAuthType {
}
impl TryFrom<&types::ConnectorAuthType> for TrustpayAuthType {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
if let types::ConnectorAuthType::SignatureKey {
api_key,
@@ -181,18 +183,22 @@ pub struct TrustpayMandatoryParams {
pub billing_postcode: Secret<String>,
}
-fn get_trustpay_payment_method(bank_redirection_data: &BankRedirectData) -> TrustpayPaymentMethod {
- match bank_redirection_data {
- api_models::payments::BankRedirectData::Giropay { .. } => TrustpayPaymentMethod::Giropay,
- api_models::payments::BankRedirectData::Eps { .. } => TrustpayPaymentMethod::Eps,
- api_models::payments::BankRedirectData::Ideal { .. } => TrustpayPaymentMethod::IDeal,
- api_models::payments::BankRedirectData::Sofort { .. } => TrustpayPaymentMethod::Sofort,
+impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
+ type Error = Error;
+ fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
+ match value {
+ api_models::payments::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ api_models::payments::BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
+ api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
}
}
fn get_mandatory_fields(
item: &types::PaymentsAuthorizeRouterData,
-) -> Result<TrustpayMandatoryParams, error_stack::Report<errors::ConnectorError>> {
+) -> Result<TrustpayMandatoryParams, Error> {
let billing_address = item
.get_billing()?
.address
@@ -248,33 +254,35 @@ fn get_bank_redirection_request_data(
item: &types::PaymentsAuthorizeRouterData,
bank_redirection_data: &BankRedirectData,
amount: String,
- return_url: String,
auth: TrustpayAuthType,
-) -> TrustpayPaymentsRequest {
- TrustpayPaymentsRequest::BankRedirectPaymentRequest(Box::new(PaymentRequestBankRedirect {
- payment_method: get_trustpay_payment_method(bank_redirection_data),
- merchant_identification: MerchantIdentification {
- project_id: auth.project_id,
- },
- payment_information: BankPaymentInformation {
- amount: Amount {
- amount,
- currency: item.request.currency.to_string(),
+) -> Result<TrustpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
+ let return_url = item.request.get_return_url()?;
+ let payment_request =
+ TrustpayPaymentsRequest::BankRedirectPaymentRequest(Box::new(PaymentRequestBankRedirect {
+ payment_method: TrustpayPaymentMethod::try_from(bank_redirection_data)?,
+ merchant_identification: MerchantIdentification {
+ project_id: auth.project_id,
},
- references: References {
- merchant_reference: item.attempt_id.clone(),
+ payment_information: BankPaymentInformation {
+ amount: Amount {
+ amount,
+ currency: item.request.currency.to_string(),
+ },
+ references: References {
+ merchant_reference: item.attempt_id.clone(),
+ },
},
- },
- callback_urls: CallbackURLs {
- success: format!("{return_url}?status=SuccessOk"),
- cancel: return_url.clone(),
- error: return_url,
- },
- }))
+ callback_urls: CallbackURLs {
+ success: format!("{return_url}?status=SuccessOk"),
+ cancel: return_url.clone(),
+ error: return_url,
+ },
+ }));
+ Ok(payment_request)
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for TrustpayPaymentsRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let default_browser_info = BrowserInformation {
color_depth: 24,
@@ -303,7 +311,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TrustpayPaymentsRequest {
);
let auth = TrustpayAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(match item.request.payment_method_data {
+ match item.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => Ok(get_card_request_data(
item,
browser_info,
@@ -313,19 +321,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TrustpayPaymentsRequest {
item.request.get_return_url()?,
)),
api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
- Ok(get_bank_redirection_request_data(
- item,
- bank_redirection_data,
- amount,
- item.request.get_return_url()?,
- auth,
- ))
+ get_bank_redirection_request_data(item, bank_redirection_data, amount, auth)
}
- _ => Err(errors::ConnectorError::NotImplemented(format!(
- "Current Payment Method - {:?}",
- item.request.payment_method_data
- ))),
- }?)
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
}
}
@@ -524,7 +523,7 @@ impl<F, T>
TryFrom<types::ResponseRouterData<F, TrustpayPaymentsResponse, T, types::PaymentsResponseData>>
for types::RouterData<F, T, types::PaymentsResponseData>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::ResponseRouterData<
F,
@@ -733,7 +732,7 @@ pub struct TrustpayAuthUpdateRequest {
}
impl TryFrom<&types::RefreshTokenRouterData> for TrustpayAuthUpdateRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(_item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
@@ -767,7 +766,7 @@ pub struct TrustpayAccessTokenErrorResponse {
impl<F, T> TryFrom<types::ResponseRouterData<F, TrustpayAuthUpdateResponse, T, types::AccessToken>>
for types::RouterData<F, T, types::AccessToken>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::ResponseRouterData<F, TrustpayAuthUpdateResponse, T, types::AccessToken>,
) -> Result<Self, Self::Error> {
@@ -820,7 +819,7 @@ pub enum TrustpayRefundRequest {
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for TrustpayRefundRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
let amount = format!(
"{:.2}",
@@ -1000,7 +999,7 @@ fn handle_bank_redirects_refund_sync_error_response(
impl<F> TryFrom<types::RefundsResponseRouterData<F, RefundResponse>>
for types::RefundsRouterData<F>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = Error;
fn try_from(
item: types::RefundsResponseRouterData<F, RefundResponse>,
) -> Result<Self, Self::Error> {
diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs
index e937728a585..21bb28561e8 100644
--- a/crates/storage_models/src/enums.rs
+++ b/crates/storage_models/src/enums.rs
@@ -612,19 +612,34 @@ pub enum MandateStatus {
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodType {
+ Affirm,
+ AfterpayClearpay,
+ AliPay,
+ ApplePay,
+ BancontactCard,
+ Blik,
Credit,
+ CryptoCurrency,
Debit,
+ Eps,
Giropay,
+ GooglePay,
Ideal,
- Sofort,
- Eps,
Klarna,
- Affirm,
- AfterpayClearpay,
- GooglePay,
- ApplePay,
+ MbWay,
+ MobilePay,
+ OnlineBankingCzechRepublic,
+ OnlineBankingFinland,
+ OnlineBankingPoland,
+ OnlineBankingSlovakia,
+ PayBright,
Paypal,
- CryptoCurrency,
+ Przelewy24,
+ Sofort,
+ Swish,
+ Trustly,
+ Walley,
+ WeChatPay,
}
#[derive(
|
feat
|
add new payment methods for Bank redirects, BNPL and wallet (#864)
|
60ddddf24a1625b8044c095c5d01754022102813
|
2025-02-06 19:16:00
|
Sarthak Soni
|
feat(routing): Contract based routing integration (#6761)
| false
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 6ad86dd4ccc..16254a6b998 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -67,6 +67,9 @@ crates/router/src/core/routing @juspay/hyperswitch-routing
crates/router/src/core/routing.rs @juspay/hyperswitch-routing
crates/router/src/core/payments/routing @juspay/hyperswitch-routing
crates/router/src/core/payments/routing.rs @juspay/hyperswitch-routing
+crates/external_services/src/grpc_client/dynamic_routing.rs @juspay/hyperswitch-routing
+crates/external_services/src/grpc_client/dynamic_routing/ @juspay/hyperswitch-routing
+crates/external_services/src/grpc_client/health_check_client.rs @juspay/hyperswitch-routing
crates/api_models/src/payment_methods.rs @juspay/hyperswitch-routing
crates/router/src/core/payment_methods.rs @juspay/hyperswitch-routing
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 6c03d7a9a25..7132fe905c7 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -4082,7 +4082,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/DynamicRoutingFeatures"
+ "$ref": "#/components/schemas/SuccessBasedRoutingConfig"
}
}
},
@@ -4229,7 +4229,7 @@
{
"name": "enable",
"in": "query",
- "description": "Feature to enable for success based routing",
+ "description": "Feature to enable for elimination based routing",
"required": true,
"schema": {
"$ref": "#/components/schemas/DynamicRoutingFeatures"
@@ -4273,6 +4273,174 @@
]
}
},
+ "/account/:account_id/business_profile/:profile_id/dynamic_routing/contracts/toggle": {
+ "post": {
+ "tags": [
+ "Routing"
+ ],
+ "summary": "Routing - Toggle Contract routing for profile",
+ "description": "Create a Contract based dynamic routing algorithm",
+ "operationId": "Toggle contract routing algorithm",
+ "parameters": [
+ {
+ "name": "account_id",
+ "in": "path",
+ "description": "Merchant id",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "Profile id under which Dynamic routing needs to be toggled",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "enable",
+ "in": "query",
+ "description": "Feature to enable for contract based routing",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/DynamicRoutingFeatures"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContractBasedRoutingConfig"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Routing Algorithm created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingDictionaryRecord"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Request body is malformed"
+ },
+ "403": {
+ "description": "Forbidden"
+ },
+ "404": {
+ "description": "Resource missing"
+ },
+ "422": {
+ "description": "Unprocessable request"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}": {
+ "patch": {
+ "tags": [
+ "Routing"
+ ],
+ "summary": "Routing - Update contract based dynamic routing config for profile",
+ "description": "Update contract based dynamic routing algorithm",
+ "operationId": "Update contract based dynamic routing configs",
+ "parameters": [
+ {
+ "name": "account_id",
+ "in": "path",
+ "description": "Merchant id",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "profile_id",
+ "in": "path",
+ "description": "Profile id under which Dynamic routing needs to be toggled",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "algorithm_id",
+ "in": "path",
+ "description": "Contract based routing algorithm id which was last activated to update the config",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ContractBasedRoutingConfig"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Routing Algorithm updated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutingDictionaryRecord"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Update body is malformed"
+ },
+ "403": {
+ "description": "Forbidden"
+ },
+ "404": {
+ "description": "Resource missing"
+ },
+ "422": {
+ "description": "Unprocessable request"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
"/blocklist": {
"delete": {
"tags": [
@@ -9536,6 +9704,54 @@
},
"additionalProperties": false
},
+ "ContractBasedRoutingConfig": {
+ "type": "object",
+ "properties": {
+ "config": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ContractBasedRoutingConfigBody"
+ }
+ ],
+ "nullable": true
+ },
+ "label_info": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/LabelInformation"
+ },
+ "nullable": true
+ }
+ }
+ },
+ "ContractBasedRoutingConfigBody": {
+ "type": "object",
+ "properties": {
+ "constants": {
+ "type": "array",
+ "items": {
+ "type": "number",
+ "format": "double"
+ },
+ "nullable": true
+ },
+ "time_scale": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ContractBasedTimeScale"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "ContractBasedTimeScale": {
+ "type": "string",
+ "enum": [
+ "day",
+ "month"
+ ]
+ },
"CountryAlpha2": {
"type": "string",
"enum": [
@@ -12886,6 +13102,33 @@
}
}
},
+ "LabelInformation": {
+ "type": "object",
+ "required": [
+ "label",
+ "target_count",
+ "target_time",
+ "mca_id"
+ ],
+ "properties": {
+ "label": {
+ "type": "string"
+ },
+ "target_count": {
+ "type": "integer",
+ "format": "int64",
+ "minimum": 0
+ },
+ "target_time": {
+ "type": "integer",
+ "format": "int64",
+ "minimum": 0
+ },
+ "mca_id": {
+ "type": "string"
+ }
+ }
+ },
"LinkedRoutingConfigRetrieveResponse": {
"oneOf": [
{
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index f3e169336bf..122d1f8d3c8 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -1,12 +1,13 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::routing::{
- LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
- RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
- RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
+ ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper,
+ DynamicRoutingUpdateConfigQuery, LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm,
+ ProfileDefaultRoutingConfig, RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord,
+ RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplitWrapper,
- SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper,
- SuccessBasedRoutingUpdateConfigQuery, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper,
+ SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingQuery,
+ ToggleDynamicRoutingWrapper,
};
impl ApiEventMetric for RoutingKind {
@@ -97,13 +98,25 @@ impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper {
}
}
+impl ApiEventMetric for ContractBasedRoutingPayloadWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for ContractBasedRoutingSetupPayloadWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
impl ApiEventMetric for ToggleDynamicRoutingWrapper {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
}
-impl ApiEventMetric for SuccessBasedRoutingUpdateConfigQuery {
+impl ApiEventMetric for DynamicRoutingUpdateConfigQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 8e502767575..d4b4f76e178 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -513,17 +513,27 @@ pub struct RoutingLinkWrapper {
pub algorithm_id: RoutingAlgorithmId,
}
-#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicAlgorithmWithTimestamp<T> {
pub algorithm_id: Option<T>,
pub timestamp: i64,
}
+impl<T> DynamicAlgorithmWithTimestamp<T> {
+ pub fn new(algorithm_id: Option<T>) -> Self {
+ Self {
+ algorithm_id,
+ timestamp: common_utils::date_time::now_unix_timestamp(),
+ }
+ }
+}
+
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
pub dynamic_routing_volume_split: Option<u8>,
pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>,
+ pub contract_based_routing: Option<ContractRoutingAlgorithm>,
}
pub trait DynamicRoutingAlgoAccessor {
@@ -555,6 +565,43 @@ impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm {
}
}
+impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm {
+ fn get_algorithm_id_with_timestamp(
+ self,
+ ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
+ self.algorithm_id_with_timestamp
+ }
+ fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
+ &mut self.enabled_feature
+ }
+}
+
+impl EliminationRoutingAlgorithm {
+ pub fn new(
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
+ common_utils::id_type::RoutingId,
+ >,
+ ) -> Self {
+ Self {
+ algorithm_id_with_timestamp,
+ enabled_feature: DynamicRoutingFeatures::None,
+ }
+ }
+}
+
+impl SuccessBasedAlgorithm {
+ pub fn new(
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
+ common_utils::id_type::RoutingId,
+ >,
+ ) -> Self {
+ Self {
+ algorithm_id_with_timestamp,
+ enabled_feature: DynamicRoutingFeatures::None,
+ }
+ }
+}
+
impl DynamicRoutingAlgorithmRef {
pub fn update(&mut self, new: Self) {
if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm {
@@ -563,9 +610,12 @@ impl DynamicRoutingAlgorithmRef {
if let Some(success_based_algorithm) = new.success_based_algorithm {
self.success_based_algorithm = Some(success_based_algorithm)
}
+ if let Some(contract_based_routing) = new.contract_based_routing {
+ self.contract_based_routing = Some(contract_based_routing)
+ }
}
- pub fn update_specific_ref(
+ pub fn update_enabled_features(
&mut self,
algo_type: DynamicRoutingType,
feature_to_enable: DynamicRoutingFeatures,
@@ -581,6 +631,11 @@ impl DynamicRoutingAlgorithmRef {
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
+ DynamicRoutingType::ContractBasedRouting => {
+ self.contract_based_routing
+ .as_mut()
+ .map(|algo| algo.enabled_feature = feature_to_enable);
+ }
}
}
@@ -589,32 +644,6 @@ impl DynamicRoutingAlgorithmRef {
}
}
-impl EliminationRoutingAlgorithm {
- pub fn new(
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
- common_utils::id_type::RoutingId,
- >,
- ) -> Self {
- Self {
- algorithm_id_with_timestamp,
- enabled_feature: DynamicRoutingFeatures::None,
- }
- }
-}
-
-impl SuccessBasedAlgorithm {
- pub fn new(
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
- common_utils::id_type::RoutingId,
- >,
- ) -> Self {
- Self {
- algorithm_id_with_timestamp,
- enabled_feature: DynamicRoutingFeatures::None,
- }
- }
-}
-
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplit {
pub routing_type: RoutingType,
@@ -648,6 +677,14 @@ pub struct SuccessBasedAlgorithm {
pub enabled_feature: DynamicRoutingFeatures,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ContractRoutingAlgorithm {
+ pub algorithm_id_with_timestamp:
+ DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
+ #[serde(default)]
+ pub enabled_feature: DynamicRoutingFeatures,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EliminationRoutingAlgorithm {
pub algorithm_id_with_timestamp:
@@ -678,24 +715,53 @@ impl DynamicRoutingAlgorithmRef {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp {
- algorithm_id: Some(new_id),
- timestamp: common_utils::date_time::now_unix_timestamp(),
- },
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp {
- algorithm_id: Some(new_id),
- timestamp: common_utils::date_time::now_unix_timestamp(),
- },
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
+ enabled_feature,
+ })
+ }
+ DynamicRoutingType::ContractBasedRouting => {
+ self.contract_based_routing = Some(ContractRoutingAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
};
}
+
+ pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) {
+ match dynamic_routing_type {
+ DynamicRoutingType::SuccessRateBasedRouting => {
+ if let Some(success_based_algo) = &self.success_based_algorithm {
+ self.success_based_algorithm = Some(SuccessBasedAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
+ enabled_feature: success_based_algo.enabled_feature,
+ });
+ }
+ }
+ DynamicRoutingType::EliminationRouting => {
+ if let Some(elimination_based_algo) = &self.elimination_routing_algorithm {
+ self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
+ enabled_feature: elimination_based_algo.enabled_feature,
+ });
+ }
+ }
+ DynamicRoutingType::ContractBasedRouting => {
+ if let Some(contract_based_algo) = &self.contract_based_routing {
+ self.contract_based_routing = Some(ContractRoutingAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
+ enabled_feature: contract_based_algo.enabled_feature,
+ });
+ }
+ }
+ }
+ }
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -708,7 +774,9 @@ pub struct DynamicRoutingVolumeSplitQuery {
pub split: u8,
}
-#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
+#[derive(
+ Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema,
+)]
#[serde(rename_all = "snake_case")]
pub enum DynamicRoutingFeatures {
Metrics,
@@ -718,7 +786,7 @@ pub enum DynamicRoutingFeatures {
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
-pub struct SuccessBasedRoutingUpdateConfigQuery {
+pub struct DynamicRoutingUpdateConfigQuery {
#[schema(value_type = String)]
pub algorithm_id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
@@ -827,10 +895,27 @@ pub struct SuccessBasedRoutingPayloadWrapper {
pub profile_id: common_utils::id_type::ProfileId,
}
-#[derive(Debug, Clone, strum::Display, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ContractBasedRoutingPayloadWrapper {
+ pub updated_config: ContractBasedRoutingConfig,
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ContractBasedRoutingSetupPayloadWrapper {
+ pub config: Option<ContractBasedRoutingConfig>,
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub features_to_enable: DynamicRoutingFeatures,
+}
+
+#[derive(
+ Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq,
+)]
pub enum DynamicRoutingType {
SuccessRateBasedRouting,
EliminationRouting,
+ ContractBasedRouting,
}
impl SuccessBasedRoutingConfig {
@@ -872,6 +957,91 @@ impl CurrentBlockThreshold {
}
}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct ContractBasedRoutingConfig {
+ pub config: Option<ContractBasedRoutingConfigBody>,
+ pub label_info: Option<Vec<LabelInformation>>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct ContractBasedRoutingConfigBody {
+ pub constants: Option<Vec<f64>>,
+ pub time_scale: Option<ContractBasedTimeScale>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct LabelInformation {
+ pub label: String,
+ pub target_count: u64,
+ pub target_time: u64,
+ #[schema(value_type = String)]
+ pub mca_id: common_utils::id_type::MerchantConnectorAccountId,
+}
+
+impl LabelInformation {
+ pub fn update_target_time(&mut self, new: &Self) {
+ self.target_time = new.target_time;
+ }
+
+ pub fn update_target_count(&mut self, new: &Self) {
+ self.target_count = new.target_count;
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ContractBasedTimeScale {
+ Day,
+ Month,
+}
+
+impl Default for ContractBasedRoutingConfig {
+ fn default() -> Self {
+ Self {
+ config: Some(ContractBasedRoutingConfigBody {
+ constants: Some(vec![0.7, 0.35]),
+ time_scale: Some(ContractBasedTimeScale::Day),
+ }),
+ label_info: None,
+ }
+ }
+}
+
+impl ContractBasedRoutingConfig {
+ pub fn update(&mut self, new: Self) {
+ if let Some(new_config) = new.config {
+ self.config.as_mut().map(|config| config.update(new_config));
+ }
+ if let Some(new_label_info) = new.label_info {
+ new_label_info.iter().for_each(|new_label_info| {
+ if let Some(existing_label_infos) = &mut self.label_info {
+ for existing_label_info in existing_label_infos {
+ if existing_label_info.mca_id == new_label_info.mca_id {
+ existing_label_info.update_target_time(new_label_info);
+ existing_label_info.update_target_count(new_label_info);
+ }
+ }
+ } else {
+ self.label_info = Some(vec![new_label_info.clone()]);
+ }
+ });
+ }
+ }
+}
+
+impl ContractBasedRoutingConfigBody {
+ pub fn update(&mut self, new: Self) {
+ if let Some(new_cons) = new.constants {
+ self.constants = Some(new_cons)
+ }
+ if let Some(new_time_scale) = new.time_scale {
+ self.time_scale = Some(new_time_scale)
+ }
+ }
+}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct RoutableConnectorChoiceWithBucketName {
pub routable_connector_choice: RoutableConnectorChoice,
diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs
index b3fa1a8fed2..8dba0bb3e98 100644
--- a/crates/external_services/build.rs
+++ b/crates/external_services/build.rs
@@ -6,6 +6,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let proto_path = router_env::workspace_path().join("proto");
let success_rate_proto_file = proto_path.join("success_rate.proto");
+ let contract_routing_proto_file = proto_path.join("contract_routing.proto");
let elimination_proto_file = proto_path.join("elimination_rate.proto");
let health_check_proto_file = proto_path.join("health_check.proto");
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
@@ -16,8 +17,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.compile(
&[
success_rate_proto_file,
- elimination_proto_file,
health_check_proto_file,
+ elimination_proto_file,
+ contract_routing_proto_file,
],
&[proto_path],
)
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
index e5050227fa8..e34f721b30e 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -1,14 +1,18 @@
+/// Module for Contract based routing
+pub mod contract_routing_client;
+
use std::fmt::Debug;
use common_utils::errors::CustomResult;
use router_env::logger;
use serde;
/// Elimination Routing Client Interface Implementation
-pub mod elimination_rate_client;
+pub mod elimination_based_client;
/// Success Routing Client Interface Implementation
pub mod success_rate_client;
-pub use elimination_rate_client::EliminationAnalyserClient;
+pub use contract_routing_client::ContractScoreCalculatorClient;
+pub use elimination_based_client::EliminationAnalyserClient;
pub use success_rate_client::SuccessRateCalculatorClient;
use super::Client;
@@ -27,6 +31,10 @@ pub enum DynamicRoutingError {
/// Error from Dynamic Routing Server while performing success_rate analysis
#[error("Error from Dynamic Routing Server while perfrming success_rate analysis : {0}")]
SuccessRateBasedRoutingFailure(String),
+
+ /// Error from Dynamic Routing Server while performing contract based routing
+ #[error("Error from Dynamic Routing Server while performing contract based routing: {0}")]
+ ContractBasedRoutingFailure(String),
/// Error from Dynamic Routing Server while perfrming elimination
#[error("Error from Dynamic Routing Server while perfrming elimination : {0}")]
EliminationRateRoutingFailure(String),
@@ -37,8 +45,10 @@ pub enum DynamicRoutingError {
pub struct RoutingStrategy {
/// success rate service for Dynamic Routing
pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>,
+ /// contract based routing service for Dynamic Routing
+ pub contract_based_client: Option<ContractScoreCalculatorClient<Client>>,
/// elimination service for Dynamic Routing
- pub elimination_rate_client: Option<EliminationAnalyserClient<Client>>,
+ pub elimination_based_client: Option<EliminationAnalyserClient<Client>>,
}
/// Contains the Dynamic Routing Client Config
@@ -65,7 +75,7 @@ impl DynamicRoutingClientConfig {
self,
client: Client,
) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
- let (success_rate_client, elimination_rate_client) = match self {
+ let (success_rate_client, contract_based_client, elimination_based_client) = match self {
Self::Enabled { host, port, .. } => {
let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?;
logger::info!("Connection established with dynamic routing gRPC Server");
@@ -74,14 +84,19 @@ impl DynamicRoutingClientConfig {
client.clone(),
uri.clone(),
)),
+ Some(ContractScoreCalculatorClient::with_origin(
+ client.clone(),
+ uri.clone(),
+ )),
Some(EliminationAnalyserClient::with_origin(client, uri)),
)
}
- Self::Disabled => (None, None),
+ Self::Disabled => (None, None, None),
};
Ok(RoutingStrategy {
success_rate_client,
- elimination_rate_client,
+ contract_based_client,
+ elimination_based_client,
})
}
}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs
new file mode 100644
index 00000000000..b210d996bc0
--- /dev/null
+++ b/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs
@@ -0,0 +1,192 @@
+use api_models::routing::{
+ ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,
+ LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
+};
+use common_utils::{
+ ext_traits::OptionExt,
+ transformers::{ForeignFrom, ForeignTryFrom},
+};
+pub use contract_routing::{
+ contract_score_calculator_client::ContractScoreCalculatorClient, CalContractScoreConfig,
+ CalContractScoreRequest, CalContractScoreResponse, InvalidateContractRequest,
+ InvalidateContractResponse, LabelInformation as ProtoLabelInfo, TimeScale,
+ UpdateContractRequest, UpdateContractResponse,
+};
+use error_stack::ResultExt;
+use router_env::logger;
+
+use crate::grpc_client::{self, GrpcHeaders};
+#[allow(
+ missing_docs,
+ unused_qualifications,
+ clippy::unwrap_used,
+ clippy::as_conversions,
+ clippy::use_self
+)]
+pub mod contract_routing {
+ tonic::include_proto!("contract_routing");
+}
+use super::{Client, DynamicRoutingError, DynamicRoutingResult};
+/// The trait ContractBasedDynamicRouting would have the functions required to support the calculation and updation window
+#[async_trait::async_trait]
+pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
+ /// To calculate the contract scores for the list of chosen connectors
+ async fn calculate_contract_score(
+ &self,
+ id: String,
+ config: ContractBasedRoutingConfig,
+ params: String,
+ label_input: Vec<RoutableConnectorChoice>,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<CalContractScoreResponse>;
+ /// To update the contract scores with the given labels
+ async fn update_contracts(
+ &self,
+ id: String,
+ label_info: Vec<LabelInformation>,
+ params: String,
+ response: Vec<RoutableConnectorChoiceWithStatus>,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<UpdateContractResponse>;
+ /// To invalidates the contract scores against the id
+ async fn invalidate_contracts(
+ &self,
+ id: String,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<InvalidateContractResponse>;
+}
+
+#[async_trait::async_trait]
+impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {
+ async fn calculate_contract_score(
+ &self,
+ id: String,
+ config: ContractBasedRoutingConfig,
+ params: String,
+ label_input: Vec<RoutableConnectorChoice>,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<CalContractScoreResponse> {
+ let labels = label_input
+ .into_iter()
+ .map(|conn_choice| conn_choice.to_string())
+ .collect::<Vec<_>>();
+
+ let config = config
+ .config
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?;
+
+ let request = grpc_client::create_grpc_request(
+ CalContractScoreRequest {
+ id,
+ params,
+ labels,
+ config,
+ },
+ headers,
+ );
+
+ let response = self
+ .clone()
+ .fetch_contract_score(request)
+ .await
+ .change_context(DynamicRoutingError::ContractBasedRoutingFailure(
+ "Failed to fetch the contract score".to_string(),
+ ))?
+ .into_inner();
+
+ logger::info!(dynamic_routing_response=?response);
+
+ Ok(response)
+ }
+
+ async fn update_contracts(
+ &self,
+ id: String,
+ label_info: Vec<LabelInformation>,
+ params: String,
+ _response: Vec<RoutableConnectorChoiceWithStatus>,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<UpdateContractResponse> {
+ let labels_information = label_info
+ .into_iter()
+ .map(ProtoLabelInfo::foreign_from)
+ .collect::<Vec<_>>();
+
+ let request = grpc_client::create_grpc_request(
+ UpdateContractRequest {
+ id,
+ params,
+ labels_information,
+ },
+ headers,
+ );
+
+ let response = self
+ .clone()
+ .update_contract(request)
+ .await
+ .change_context(DynamicRoutingError::ContractBasedRoutingFailure(
+ "Failed to update the contracts".to_string(),
+ ))?
+ .into_inner();
+
+ logger::info!(dynamic_routing_response=?response);
+
+ Ok(response)
+ }
+ async fn invalidate_contracts(
+ &self,
+ id: String,
+ headers: GrpcHeaders,
+ ) -> DynamicRoutingResult<InvalidateContractResponse> {
+ let request = grpc_client::create_grpc_request(InvalidateContractRequest { id }, headers);
+
+ let response = self
+ .clone()
+ .invalidate_contract(request)
+ .await
+ .change_context(DynamicRoutingError::ContractBasedRoutingFailure(
+ "Failed to invalidate the contracts".to_string(),
+ ))?
+ .into_inner();
+ Ok(response)
+ }
+}
+
+impl ForeignFrom<ContractBasedTimeScale> for TimeScale {
+ fn foreign_from(scale: ContractBasedTimeScale) -> Self {
+ Self {
+ time_scale: match scale {
+ ContractBasedTimeScale::Day => 0,
+ _ => 1,
+ },
+ }
+ }
+}
+
+impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {
+ Ok(Self {
+ constants: config
+ .constants
+ .get_required_value("constants")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "constants".to_string(),
+ })?,
+ time_scale: config.time_scale.clone().map(TimeScale::foreign_from),
+ })
+ }
+}
+
+impl ForeignFrom<LabelInformation> for ProtoLabelInfo {
+ fn foreign_from(config: LabelInformation) -> Self {
+ Self {
+ label: config.label,
+ target_count: config.target_count,
+ target_time: config.target_time,
+ current_count: 1,
+ }
+ }
+}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs
similarity index 100%
rename from crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs
rename to crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 7102c23d17e..026eae764c4 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -166,6 +166,8 @@ Never share your secret api keys. Keep them guarded and secure.
routes::routing::success_based_routing_update_configs,
routes::routing::toggle_success_based_routing,
routes::routing::toggle_elimination_routing,
+ routes::routing::contract_based_routing_setup_config,
+ routes::routing::contract_based_routing_update_configs,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
@@ -615,6 +617,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::DynamicRoutingConfigParams,
api_models::routing::CurrentBlockThreshold,
api_models::routing::SuccessBasedRoutingConfigBody,
+ api_models::routing::ContractBasedRoutingConfig,
+ api_models::routing::ContractBasedRoutingConfigBody,
+ api_models::routing::LabelInformation,
+ api_models::routing::ContractBasedTimeScale,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index 6b968f80172..c21669a9932 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -292,7 +292,7 @@ pub async fn toggle_success_based_routing() {}
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"),
),
- request_body = DynamicRoutingFeatures,
+ request_body = SuccessBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
@@ -317,7 +317,7 @@ pub async fn success_based_routing_update_configs() {}
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
- ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
+ ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
@@ -332,3 +332,57 @@ pub async fn success_based_routing_update_configs() {}
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_elimination_routing() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Toggle Contract routing for profile
+///
+/// Create a Contract based dynamic routing algorithm
+#[utoipa::path(
+ post,
+ path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/contracts/toggle",
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
+ ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for contract based routing"),
+ ),
+ request_body = ContractBasedRoutingConfig,
+ responses(
+ (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
+ (status = 400, description = "Request body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Toggle contract routing algorithm",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn contract_based_routing_setup_config() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Update contract based dynamic routing config for profile
+///
+/// Update contract based dynamic routing algorithm
+#[utoipa::path(
+ patch,
+ path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}",
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
+ ("algorithm_id" = String, Path, description = "Contract based routing algorithm id which was last activated to update the config"),
+ ),
+ request_body = ContractBasedRoutingConfig,
+ responses(
+ (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
+ (status = 400, description = "Update body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Update contract based dynamic routing configs",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn contract_based_routing_update_configs() {}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index b4c1c1c2c03..54cae42ceb3 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -398,6 +398,16 @@ pub enum RoutingError {
GenericNotFoundError { field: String },
#[error("Unable to deserialize from '{from}' to '{to}'")]
DeserializationError { from: String, to: String },
+ #[error("Unable to retrieve contract based routing config")]
+ ContractBasedRoutingConfigError,
+ #[error("Params not found in contract based routing config")]
+ ContractBasedRoutingParamsNotFoundError,
+ #[error("Unable to calculate contract score from dynamic routing service")]
+ ContractScoreCalculationError,
+ #[error("contract routing client from dynamic routing gRPC service not initialized")]
+ ContractRoutingClientInitializationError,
+ #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")]
+ InvalidContractBasedConnectorLabel(String),
}
#[derive(Debug, Clone, thiserror::Error)]
diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs
index a98a4ffb259..efb463b3a37 100644
--- a/crates/router/src/core/metrics.rs
+++ b/crates/router/src/core/metrics.rs
@@ -82,6 +82,7 @@ counter_metric!(
GLOBAL_METER
);
counter_metric!(DYNAMIC_SUCCESS_BASED_ROUTING, GLOBAL_METER);
+counter_metric!(DYNAMIC_CONTRACT_BASED_ROUTING, GLOBAL_METER);
#[cfg(feature = "partial-auth")]
counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER);
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index dce89107afd..f86072fdcc2 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -6599,8 +6599,8 @@ where
.attach_printable("failed to perform volume split on routing type")?;
if routing_choice.routing_type.is_dynamic_routing() {
- let success_based_routing_config_params_interpolator =
- routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(
+ let dynamic_routing_config_params_interpolator =
+ routing_helpers::DynamicRoutingConfigParamsInterpolator::new(
payment_data.get_payment_attempt().payment_method,
payment_data.get_payment_attempt().payment_method_type,
payment_data.get_payment_attempt().authentication_type,
@@ -6630,14 +6630,15 @@ where
.and_then(|card_isin| card_isin.as_str())
.map(|card_isin| card_isin.to_string()),
);
- routing::perform_success_based_routing(
+
+ routing::perform_dynamic_routing(
state,
connectors.clone(),
business_profile,
- success_based_routing_config_params_interpolator,
+ dynamic_routing_config_params_interpolator,
)
.await
- .map_err(|e| logger::error!(success_rate_routing_error=?e))
+ .map_err(|e| logger::error!(dynamic_routing_error=?e))
.unwrap_or(connectors)
} else {
connectors
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 70d5f79845b..516cebe24d7 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -5,6 +5,8 @@ use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
use api_models::routing::RoutableConnectorChoice;
use async_trait::async_trait;
use common_enums::{AuthorizationStatus, SessionUpdateStatus};
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use common_utils::ext_traits::ValueExt;
use common_utils::{
ext_traits::{AsyncExt, Encode},
types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit},
@@ -1961,11 +1963,22 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
if payment_intent.status.is_in_terminal_state()
&& business_profile.dynamic_routing_algorithm.is_some()
{
+ let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("DynamicRoutingAlgorithmRef not found in profile")?;
+
let state = state.clone();
- let business_profile = business_profile.clone();
+ let profile_id = business_profile.get_id().to_owned();
let payment_attempt = payment_attempt.clone();
- let success_based_routing_config_params_interpolator =
- routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(
+ let dynamic_routing_config_params_interpolator =
+ routing_helpers::DynamicRoutingConfigParamsInterpolator::new(
payment_attempt.payment_method,
payment_attempt.payment_method_type,
payment_attempt.authentication_type,
@@ -1997,14 +2010,27 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
tokio::spawn(
async move {
routing_helpers::push_metrics_with_update_window_for_success_based_routing(
+ &state,
+ &payment_attempt,
+ routable_connectors.clone(),
+ &profile_id,
+ dynamic_routing_algo_ref.clone(),
+ dynamic_routing_config_params_interpolator.clone(),
+ )
+ .await
+ .map_err(|e| logger::error!(success_based_routing_metrics_error=?e))
+ .ok();
+
+ routing_helpers::push_metrics_with_update_window_for_contract_based_routing(
&state,
&payment_attempt,
routable_connectors,
- &business_profile,
- success_based_routing_config_params_interpolator,
+ &profile_id,
+ dynamic_routing_algo_ref,
+ dynamic_routing_config_params_interpolator,
)
.await
- .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))
+ .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e))
.ok();
}
.in_current_span(),
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index dd592bc3064..41be7e6e2d3 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -14,6 +14,8 @@ use api_models::{
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
+#[cfg(feature = "dynamic_routing")]
+use common_utils::ext_traits::AsyncExt;
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use euclid::{
@@ -23,8 +25,9 @@ use euclid::{
frontend::{ast, dir as euclid_dir},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-use external_services::grpc_client::dynamic_routing::success_rate_client::{
- CalSuccessRateResponse, SuccessBasedDynamicRouting,
+use external_services::grpc_client::dynamic_routing::{
+ contract_routing_client::{CalContractScoreResponse, ContractBasedDynamicRouting},
+ success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting},
};
use hyperswitch_domain_models::address::Address;
use kgraph_utils::{
@@ -1281,41 +1284,93 @@ pub fn make_dsl_input_for_surcharge(
Ok(backend_input)
}
-/// success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-#[instrument(skip_all)]
-pub async fn perform_success_based_routing(
+pub async fn perform_dynamic_routing(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
- business_profile: &domain::Profile,
- success_based_routing_config_params_interpolator: routing::helpers::SuccessBasedRoutingConfigParamsInterpolator,
+ profile: &domain::Profile,
+ dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
- let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef =
- business_profile
- .dynamic_routing_algorithm
- .clone()
- .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
- .transpose()
- .change_context(errors::RoutingError::DeserializationError {
- from: "JSON".to_string(),
- to: "DynamicRoutingAlgorithmRef".to_string(),
- })
- .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
- .unwrap_or_default();
+ let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::RoutingError::DeserializationError {
+ from: "JSON".to_string(),
+ to: "DynamicRoutingAlgorithmRef".to_string(),
+ })
+ .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
+ .ok_or(errors::RoutingError::GenericNotFoundError {
+ field: "dynamic_routing_algorithm".to_string(),
+ })?;
+
+ logger::debug!(
+ "performing dynamic_routing for profile {}",
+ profile.get_id().get_string_repr()
+ );
- let success_based_algo_ref = success_based_dynamic_routing_algo_ref
+ let connector_list = match dynamic_routing_algo_ref
.success_based_algorithm
- .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_algorithm".to_string() })
- .attach_printable(
- "success_based_algorithm not found in dynamic_routing_algorithm from business_profile table",
- )?;
+ .as_ref()
+ .async_map(|algorithm| {
+ perform_success_based_routing(
+ state,
+ routable_connectors.clone(),
+ profile.get_id(),
+ dynamic_routing_config_params_interpolator.clone(),
+ algorithm.clone(),
+ )
+ })
+ .await
+ .transpose()
+ .inspect_err(|e| logger::error!(dynamic_routing_error=?e))
+ .ok()
+ .flatten()
+ {
+ Some(success_based_list) => success_based_list,
+ None => {
+ // Only run contract based if success based returns None
+ dynamic_routing_algo_ref
+ .contract_based_routing
+ .as_ref()
+ .async_map(|algorithm| {
+ perform_contract_based_routing(
+ state,
+ routable_connectors.clone(),
+ profile.get_id(),
+ dynamic_routing_config_params_interpolator,
+ algorithm.clone(),
+ )
+ })
+ .await
+ .transpose()
+ .inspect_err(|e| logger::error!(dynamic_routing_error=?e))
+ .ok()
+ .flatten()
+ .unwrap_or(routable_connectors)
+ }
+ };
+ Ok(connector_list)
+}
+
+/// success based dynamic routing
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+#[instrument(skip_all)]
+pub async fn perform_success_based_routing(
+ state: &SessionState,
+ routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
+ profile_id: &common_utils::id_type::ProfileId,
+ success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
+ success_based_algo_ref: api_routing::SuccessBasedAlgorithm,
+) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
if success_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing success_based_routing for profile {}",
- business_profile.get_id().get_string_repr()
+ profile_id.get_string_repr()
);
let client = state
.grpc_client
@@ -1325,18 +1380,18 @@ pub async fn perform_success_based_routing(
.ok_or(errors::RoutingError::SuccessRateClientInitializationError)
.attach_printable("success_rate gRPC client not found")?;
- let success_based_routing_configs = routing::helpers::fetch_success_based_routing_configs(
+ let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
+ api_routing::SuccessBasedRoutingConfig,
+ >(
state,
- business_profile,
+ profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "success_based_routing_algorithm_id".to_string(),
})
- .attach_printable(
- "success_based_routing_algorithm_id not found in business_profile",
- )?,
+ .attach_printable("success_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
@@ -1352,7 +1407,7 @@ pub async fn perform_success_based_routing(
let success_based_connectors: CalSuccessRateResponse = client
.calculate_success_rate(
- business_profile.get_id().get_string_repr().into(),
+ profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
routable_connectors,
@@ -1398,3 +1453,95 @@ pub async fn perform_success_based_routing(
Ok(routable_connectors)
}
}
+
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn perform_contract_based_routing(
+ state: &SessionState,
+ routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
+ profile_id: &common_utils::id_type::ProfileId,
+ _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
+ contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,
+) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
+ if contract_based_algo_ref.enabled_feature
+ == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
+ {
+ logger::debug!(
+ "performing contract_based_routing for profile {}",
+ profile_id.get_string_repr()
+ );
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .contract_based_client
+ .as_ref()
+ .ok_or(errors::RoutingError::ContractRoutingClientInitializationError)
+ .attach_printable("contract routing gRPC client not found")?;
+
+ let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
+ api_routing::ContractBasedRoutingConfig,
+ >(
+ state,
+ profile_id,
+ contract_based_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::RoutingError::GenericNotFoundError {
+ field: "contract_based_routing_algorithm_id".to_string(),
+ })
+ .attach_printable("contract_based_routing_algorithm_id not found in profile_id")?,
+ )
+ .await
+ .change_context(errors::RoutingError::ContractBasedRoutingConfigError)
+ .attach_printable("unable to fetch contract based dynamic routing configs")?;
+
+ let contract_based_connectors: CalContractScoreResponse = client
+ .calculate_contract_score(
+ profile_id.get_string_repr().into(),
+ contract_based_routing_configs,
+ "".to_string(),
+ routable_connectors,
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::RoutingError::ContractScoreCalculationError)
+ .attach_printable(
+ "unable to calculate/fetch contract score from dynamic routing service",
+ )?;
+
+ let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());
+
+ for label_with_score in contract_based_connectors.labels_with_score {
+ let (connector, merchant_connector_id) = label_with_score.label
+ .split_once(':')
+ .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))
+ .attach_printable(
+ "unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
+ )?;
+
+ connectors.push(api_routing::RoutableConnectorChoice {
+ choice_kind: api_routing::RoutableChoiceKind::FullStruct,
+ connector: common_enums::RoutableConnectors::from_str(connector)
+ .change_context(errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "RoutableConnectors".to_string(),
+ })
+ .attach_printable("unable to convert String to RoutableConnectors")?,
+ merchant_connector_id: Some(
+ common_utils::id_type::MerchantConnectorAccountId::wrap(
+ merchant_connector_id.to_string(),
+ )
+ .change_context(errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "MerchantConnectorAccountId".to_string(),
+ })
+ .attach_printable("unable to convert MerchantConnectorAccountId from string")?,
+ ),
+ });
+ }
+
+ logger::debug!(contract_based_routing_connectors=?connectors);
+ Ok(connectors)
+ } else {
+ Ok(routable_connectors)
+ }
+}
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 99bd2b00209..8d03e82a328 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -2,6 +2,8 @@ pub mod helpers;
pub mod transformers;
use std::collections::HashSet;
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use api_models::routing::DynamicRoutingAlgoAccessor;
use api_models::{
enums, mandates as mandates_api, routing,
routing::{self as routing_types, RoutingRetrieveQuery},
@@ -12,7 +14,10 @@ use common_utils::ext_traits::AsyncExt;
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting;
+use external_services::grpc_client::dynamic_routing::{
+ contract_routing_client::ContractBasedDynamicRouting,
+ success_rate_client::SuccessBasedDynamicRouting,
+};
use hyperswitch_domain_models::{mandates, payment_address};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use router_env::logger;
@@ -462,6 +467,16 @@ pub async fn link_routing_config(
},
enabled_feature: _
}) if id == &algorithm_id
+ ) || matches!(
+ dynamic_routing_ref.contract_based_routing,
+ Some(routing::ContractRoutingAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(ref id),
+ timestamp: _
+ },
+ enabled_feature: _
+ }) if id == &algorithm_id
),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
@@ -470,7 +485,8 @@ pub async fn link_routing_config(
},
)?;
- dynamic_routing_ref.update_algorithm_id(
+ if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM {
+ dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.success_based_algorithm
@@ -482,6 +498,34 @@ pub async fn link_routing_config(
.enabled_feature,
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
);
+ } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM
+ {
+ dynamic_routing_ref.update_algorithm_id(
+ algorithm_id,
+ dynamic_routing_ref
+ .elimination_routing_algorithm
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table",
+ )?
+ .enabled_feature,
+ routing_types::DynamicRoutingType::EliminationRouting,
+ );
+ } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM {
+ dynamic_routing_ref.update_algorithm_id(
+ algorithm_id,
+ dynamic_routing_ref
+ .contract_based_routing
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "missing contract_based_routing in dynamic_algorithm_ref from business_profile table",
+ )?
+ .enabled_feature,
+ routing_types::DynamicRoutingType::ContractBasedRouting,
+ );
+ }
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
@@ -1419,6 +1463,304 @@ pub async fn success_based_routing_update_configs(
Ok(service_api::ApplicationResponse::Json(new_record))
}
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn contract_based_dynamic_routing_setup(
+ state: SessionState,
+ key_store: domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+ profile_id: common_utils::id_type::ProfileId,
+ feature_to_enable: routing_types::DynamicRoutingFeatures,
+ config: Option<routing_types::ContractBasedRoutingConfig>,
+) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("Profile")
+ .change_context(errors::ApiErrorResponse::ProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+
+ let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize dynamic routing algorithm ref from business profile",
+ )
+ .ok()
+ .flatten();
+
+ utils::when(
+ dynamic_routing_algo_ref
+ .as_mut()
+ .and_then(|algo| {
+ algo.contract_based_routing.as_mut().map(|contract_algo| {
+ *contract_algo.get_enabled_features() == feature_to_enable
+ && contract_algo
+ .clone()
+ .get_algorithm_id_with_timestamp()
+ .algorithm_id
+ .is_some()
+ })
+ })
+ .unwrap_or(false),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Contract Routing with specified features is already enabled".to_string(),
+ })
+ },
+ )?;
+
+ if feature_to_enable == routing::DynamicRoutingFeatures::None {
+ let algorithm = dynamic_routing_algo_ref
+ .clone()
+ .get_required_value("dynamic_routing_algo_ref")
+ .attach_printable("Failed to get dynamic_routing_algo_ref")?;
+ return helpers::disable_dynamic_routing_algorithm(
+ &state,
+ key_store,
+ business_profile,
+ algorithm,
+ routing_types::DynamicRoutingType::ContractBasedRouting,
+ )
+ .await;
+ }
+
+ let config = config
+ .get_required_value("ContractBasedRoutingConfig")
+ .attach_printable("Failed to get ContractBasedRoutingConfig from request")?;
+
+ let merchant_id = business_profile.merchant_id.clone();
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+
+ let algo = RoutingAlgorithm {
+ algorithm_id: algorithm_id.clone(),
+ profile_id: profile_id.clone(),
+ merchant_id,
+ name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
+ description: None,
+ kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
+ algorithm_data: serde_json::json!(config),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: common_enums::TransactionType::Payment,
+ };
+
+ // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based
+ // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up
+ let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {
+ algo.update_algorithm_id(
+ algorithm_id,
+ feature_to_enable,
+ routing_types::DynamicRoutingType::ContractBasedRouting,
+ );
+ if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection {
+ algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);
+ }
+ algo
+ } else {
+ let contract_algo = routing_types::ContractRoutingAlgorithm {
+ algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some(
+ algorithm_id.clone(),
+ )),
+ enabled_feature: feature_to_enable,
+ };
+ routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: None,
+ elimination_routing_algorithm: None,
+ dynamic_routing_volume_split: None,
+ contract_based_routing: Some(contract_algo),
+ }
+ };
+
+ // validate the contained mca_ids
+ if let Some(info_vec) = &config.label_info {
+ let validation_futures: Vec<_> = info_vec
+ .iter()
+ .map(|info| async {
+ let mca_id = info.mca_id.clone();
+ let label = info.label.clone();
+ let mca = db
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ key_manager_state,
+ merchant_account.get_id(),
+ &mca_id,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: mca_id.get_string_repr().to_owned(),
+ })?;
+
+ utils::when(mca.connector_name != label, || {
+ Err(error_stack::Report::new(
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: "Incorrect mca configuration received".to_string(),
+ },
+ ))
+ })?;
+
+ Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())
+ })
+ .collect();
+
+ futures::future::try_join_all(validation_futures).await?;
+ }
+
+ let record = db
+ .insert_routing_algorithm(algo)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to insert record in routing algorithm table")?;
+
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ final_algorithm,
+ )
+ .await?;
+
+ let new_record = record.foreign_into();
+
+ metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
+ 1,
+ router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())),
+ );
+ Ok(service_api::ApplicationResponse::Json(new_record))
+}
+
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn contract_based_routing_update_configs(
+ state: SessionState,
+ request: routing_types::ContractBasedRoutingConfig,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ algorithm_id: common_utils::id_type::RoutingId,
+ profile_id: common_utils::id_type::ProfileId,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
+ 1,
+ router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())),
+ );
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let dynamic_routing_algo_to_update = db
+ .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update
+ .algorithm_data
+ .parse_value::<routing::ContractBasedRoutingConfig>("ContractBasedRoutingConfig")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig")?;
+
+ // validate the contained mca_ids
+ if let Some(info_vec) = &request.label_info {
+ for info in info_vec {
+ let mca = db
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ key_manager_state,
+ merchant_account.get_id(),
+ &info.mca_id,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: info.mca_id.get_string_repr().to_owned(),
+ })?;
+
+ utils::when(mca.connector_name != info.label, || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Incorrect mca configuration received".to_string(),
+ })
+ })?;
+ }
+ }
+
+ config_to_update.update(request);
+
+ let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+ let algo = RoutingAlgorithm {
+ algorithm_id: updated_algorithm_id,
+ profile_id: dynamic_routing_algo_to_update.profile_id,
+ merchant_id: dynamic_routing_algo_to_update.merchant_id,
+ name: dynamic_routing_algo_to_update.name,
+ description: dynamic_routing_algo_to_update.description,
+ kind: dynamic_routing_algo_to_update.kind,
+ algorithm_data: serde_json::json!(config_to_update),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
+ };
+ let record = db
+ .insert_routing_algorithm(algo)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to insert record in routing algorithm table")?;
+
+ // redact cache for contract based routing configs
+ let cache_key = format!(
+ "{}_{}",
+ profile_id.get_string_repr(),
+ algorithm_id.get_string_repr()
+ );
+ let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(
+ cache_key.into(),
+ )];
+ let _ = cache::redact_from_redis_and_publish(
+ state.store.get_cache_store().as_ref(),
+ cache_entries_to_redact,
+ )
+ .await
+ .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the contract based routing config cache {e:?}"));
+
+ let new_record = record.foreign_into();
+
+ metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
+ 1,
+ router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())),
+ );
+
+ state
+ .grpc_client
+ .clone()
+ .dynamic_routing
+ .contract_based_client
+ .clone()
+ .async_map(|ct_client| async move {
+ ct_client
+ .invalidate_contracts(
+ profile_id.get_string_repr().into(),
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Failed to invalidate the contract based routing keys".to_string(),
+ })
+ })
+ .await
+ .transpose()?;
+
+ Ok(service_api::ApplicationResponse::Json(new_record))
+}
+
#[async_trait]
pub trait GetRoutableConnectorsForChoice {
async fn get_routable_connectors(
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 84de32483a8..9b6396013f4 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -2,6 +2,7 @@
//!
//! Functions that are used to perform the retrieval of merchant's
//! routing dict, configs, defaults
+use std::fmt::Debug;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::str::FromStr;
#[cfg(any(feature = "dynamic_routing", feature = "v1"))]
@@ -18,7 +19,10 @@ use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew;
use diesel_models::routing_algorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
-use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting;
+use external_services::grpc_client::dynamic_routing::{
+ contract_routing_client::ContractBasedDynamicRouting,
+ success_rate_client::SuccessBasedDynamicRouting,
+};
#[cfg(feature = "v1")]
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
@@ -26,7 +30,7 @@ use router_env::logger;
#[cfg(any(feature = "dynamic_routing", feature = "v1"))]
use router_env::{instrument, tracing};
use rustc_hash::FxHashSet;
-use storage_impl::redis::cache;
+use storage_impl::redis::cache::{self, Cacheable};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::db::errors::StorageErrorExt;
@@ -45,6 +49,8 @@ pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Success rate based dynamic routing algorithm";
pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Elimination based dynamic routing algorithm";
+pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
+ "Contract based dynamic routing algorithm";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
@@ -562,78 +568,146 @@ pub fn get_default_config_key(
}
}
-/// Retrieves cached success_based routing configs specific to tenant and profile
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-pub async fn get_cached_success_based_routing_config_for_profile(
- state: &SessionState,
- key: &str,
-) -> Option<Arc<routing_types::SuccessBasedRoutingConfig>> {
- cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
- .get_val::<Arc<routing_types::SuccessBasedRoutingConfig>>(cache::CacheKey {
- key: key.to_string(),
- prefix: state.tenant.redis_key_prefix.clone(),
- })
+#[async_trait::async_trait]
+pub trait DynamicRoutingCache {
+ async fn get_cached_dynamic_routing_config_for_profile(
+ state: &SessionState,
+ key: &str,
+ ) -> Option<Arc<Self>>;
+
+ async fn refresh_dynamic_routing_cache<T, F, Fut>(
+ state: &SessionState,
+ key: &str,
+ func: F,
+ ) -> RouterResult<T>
+ where
+ F: FnOnce() -> Fut + Send,
+ T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
+ Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send;
+}
+
+#[async_trait::async_trait]
+impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig {
+ async fn get_cached_dynamic_routing_config_for_profile(
+ state: &SessionState,
+ key: &str,
+ ) -> Option<Arc<Self>> {
+ cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
+ .get_val::<Arc<Self>>(cache::CacheKey {
+ key: key.to_string(),
+ prefix: state.tenant.redis_key_prefix.clone(),
+ })
+ .await
+ }
+
+ async fn refresh_dynamic_routing_cache<T, F, Fut>(
+ state: &SessionState,
+ key: &str,
+ func: F,
+ ) -> RouterResult<T>
+ where
+ F: FnOnce() -> Fut + Send,
+ T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
+ Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
+ {
+ cache::get_or_populate_in_memory(
+ state.store.get_cache_store().as_ref(),
+ key,
+ func,
+ &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
+ )
.await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to populate SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE")
+ }
}
-/// Refreshes the cached success_based routing configs specific to tenant and profile
-#[cfg(feature = "v1")]
-pub async fn refresh_success_based_routing_cache(
- state: &SessionState,
- key: &str,
- success_based_routing_config: routing_types::SuccessBasedRoutingConfig,
-) -> Arc<routing_types::SuccessBasedRoutingConfig> {
- let config = Arc::new(success_based_routing_config);
- cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
- .push(
- cache::CacheKey {
+#[async_trait::async_trait]
+impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
+ async fn get_cached_dynamic_routing_config_for_profile(
+ state: &SessionState,
+ key: &str,
+ ) -> Option<Arc<Self>> {
+ cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
+ .get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
- },
- config.clone(),
+ })
+ .await
+ }
+
+ async fn refresh_dynamic_routing_cache<T, F, Fut>(
+ state: &SessionState,
+ key: &str,
+ func: F,
+ ) -> RouterResult<T>
+ where
+ F: FnOnce() -> Fut + Send,
+ T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
+ Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
+ {
+ cache::get_or_populate_in_memory(
+ state.store.get_cache_store().as_ref(),
+ key,
+ func,
+ &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
)
- .await;
- config
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to populate CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE")
+ }
}
-/// Checked fetch of success based routing configs
+/// Cfetch dynamic routing configs
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
-pub async fn fetch_success_based_routing_configs(
+pub async fn fetch_dynamic_routing_configs<T>(
state: &SessionState,
- business_profile: &domain::Profile,
- success_based_routing_id: id_type::RoutingId,
-) -> RouterResult<routing_types::SuccessBasedRoutingConfig> {
+ profile_id: &id_type::ProfileId,
+ routing_id: id_type::RoutingId,
+) -> RouterResult<T>
+where
+ T: serde::de::DeserializeOwned
+ + Clone
+ + DynamicRoutingCache
+ + Cacheable
+ + serde::Serialize
+ + Debug,
+{
let key = format!(
"{}_{}",
- business_profile.get_id().get_string_repr(),
- success_based_routing_id.get_string_repr()
+ profile_id.get_string_repr(),
+ routing_id.get_string_repr()
);
if let Some(config) =
- get_cached_success_based_routing_config_for_profile(state, key.as_str()).await
+ T::get_cached_dynamic_routing_config_for_profile(state, key.as_str()).await
{
Ok(config.as_ref().clone())
} else {
- let success_rate_algorithm = state
- .store
- .find_routing_algorithm_by_profile_id_algorithm_id(
- business_profile.get_id(),
- &success_based_routing_id,
- )
- .await
- .change_context(errors::ApiErrorResponse::ResourceIdNotFound)
- .attach_printable("unable to retrieve success_rate_algorithm for profile from db")?;
-
- let success_rate_config = success_rate_algorithm
- .algorithm_data
- .parse_value::<routing_types::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to parse success_based_routing_config struct")?;
+ let func = || async {
+ let routing_algorithm = state
+ .store
+ .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, &routing_id)
+ .await
+ .change_context(errors::StorageError::ValueNotFound(
+ "RoutingAlgorithm".to_string(),
+ ))
+ .attach_printable("unable to retrieve routing_algorithm for profile from db")?;
+
+ let dynamic_routing_config = routing_algorithm
+ .algorithm_data
+ .parse_value::<T>("dynamic_routing_config")
+ .change_context(errors::StorageError::DeserializationFailed)
+ .attach_printable("unable to parse dynamic_routing_config")?;
+
+ Ok(dynamic_routing_config)
+ };
- refresh_success_based_routing_cache(state, key.as_str(), success_rate_config.clone()).await;
+ let dynamic_routing_config =
+ T::refresh_dynamic_routing_cache(state, key.as_str(), func).await?;
- Ok(success_rate_config)
+ Ok(dynamic_routing_config)
}
}
@@ -644,20 +718,11 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
- business_profile: &domain::Profile,
- success_based_routing_config_params_interpolator: SuccessBasedRoutingConfigParamsInterpolator,
+ profile_id: &id_type::ProfileId,
+ dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
- let success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef =
- business_profile
- .dynamic_routing_algorithm
- .clone()
- .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize DynamicRoutingAlgorithmRef from JSON")?
- .unwrap_or_default();
-
- let success_based_algo_ref = success_based_dynamic_routing_algo_ref
+ let success_based_algo_ref = dynamic_routing_algo_ref
.success_based_algorithm
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?;
@@ -678,22 +743,23 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
},
)?;
- let success_based_routing_configs = fetch_success_based_routing_configs(
- state,
- business_profile,
- success_based_algo_ref
- .algorithm_id_with_timestamp
- .algorithm_id
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "success_based_routing_algorithm_id not found in business_profile",
- )?,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
+ let success_based_routing_configs =
+ fetch_dynamic_routing_configs::<routing_types::SuccessBasedRoutingConfig>(
+ state,
+ profile_id,
+ success_based_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "success_based_routing_algorithm_id not found in business_profile",
+ )?,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
- let success_based_routing_config_params = success_based_routing_config_params_interpolator
+ let success_based_routing_config_params = dynamic_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
@@ -704,7 +770,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
let success_based_connectors = client
.calculate_entity_and_global_success_rate(
- business_profile.get_id().get_string_repr().into(),
+ profile_id.get_string_repr().into(),
success_based_routing_configs.clone(),
success_based_routing_config_params.clone(),
routable_connectors.clone(),
@@ -717,7 +783,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
)?;
let payment_status_attribute =
- get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);
+ get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
let first_merchant_success_based_connector = &success_based_connectors
.entity_scores_with_labels
@@ -743,7 +809,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
"unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
)?;
- let outcome = get_success_based_metrics_outcome_for_payment(
+ let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute,
payment_connector.to_string(),
first_merchant_success_based_connector_label.to_string(),
@@ -852,7 +918,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
client
.update_success_rate(
- business_profile.get_id().get_string_repr().into(),
+ profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
vec![routing_types::RoutableConnectorChoiceWithStatus::new(
@@ -880,8 +946,212 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
}
}
+/// metrics for contract based dynamic routing
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+#[instrument(skip_all)]
+pub async fn push_metrics_with_update_window_for_contract_based_routing(
+ state: &SessionState,
+ payment_attempt: &storage::PaymentAttempt,
+ routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
+ profile_id: &id_type::ProfileId,
+ dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
+) -> RouterResult<()> {
+ let contract_routing_algo_ref = dynamic_routing_algo_ref
+ .contract_based_routing
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table")?;
+
+ if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .contract_based_client
+ .clone()
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "contract_routing gRPC client not found".to_string(),
+ })?;
+
+ let payment_connector = &payment_attempt.connector.clone().ok_or(
+ errors::ApiErrorResponse::GenericNotFoundError {
+ message: "unable to derive payment connector from payment attempt".to_string(),
+ },
+ )?;
+
+ let contract_based_routing_config =
+ fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(
+ state,
+ profile_id,
+ contract_routing_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "contract_based_routing_algorithm_id not found in business_profile",
+ )?,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to retrieve contract based dynamic routing configs")?;
+
+ let mut existing_label_info = None;
+
+ contract_based_routing_config
+ .label_info
+ .as_ref()
+ .map(|label_info_vec| {
+ for label_info in label_info_vec {
+ if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {
+ existing_label_info = Some(label_info.clone());
+ }
+ }
+ });
+
+ let final_label_info = existing_label_info
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to get LabelInformation from ContractBasedRoutingConfig")?;
+
+ logger::debug!(
+ "contract based routing: matched LabelInformation - {:?}",
+ final_label_info
+ );
+
+ let request_label_info = routing_types::LabelInformation {
+ label: format!(
+ "{}:{}",
+ final_label_info.label.clone(),
+ final_label_info.mca_id.get_string_repr()
+ ),
+ target_count: final_label_info.target_count,
+ target_time: final_label_info.target_time,
+ mca_id: final_label_info.mca_id.to_owned(),
+ };
+
+ let payment_status_attribute =
+ get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
+
+ if payment_status_attribute == common_enums::AttemptStatus::Charged {
+ client
+ .update_contracts(
+ profile_id.get_string_repr().into(),
+ vec![request_label_info],
+ "".to_string(),
+ vec![],
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to update contract based routing window in dynamic routing service",
+ )?;
+ }
+
+ let contract_scores = client
+ .calculate_contract_score(
+ profile_id.get_string_repr().into(),
+ contract_based_routing_config.clone(),
+ "".to_string(),
+ routable_connectors.clone(),
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to calculate/fetch contract scores from dynamic routing service",
+ )?;
+
+ let first_contract_based_connector = &contract_scores
+ .labels_with_score
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
+ )?;
+
+ let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label
+ .split_once(':')
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
+ first_contract_based_connector
+ ))?
+ .0, first_contract_based_connector.score, first_contract_based_connector.current_count );
+
+ core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(
+ 1,
+ router_env::metric_attributes!(
+ (
+ "tenant",
+ state.tenant.tenant_id.get_string_repr().to_owned(),
+ ),
+ (
+ "merchant_profile_id",
+ format!(
+ "{}:{}",
+ payment_attempt.merchant_id.get_string_repr(),
+ payment_attempt.profile_id.get_string_repr()
+ ),
+ ),
+ (
+ "contract_based_routing_connector",
+ first_contract_based_connector.to_string(),
+ ),
+ (
+ "contract_based_routing_connector_score",
+ connector_score.to_string(),
+ ),
+ (
+ "current_payment_count_contract_based_routing_connector",
+ current_payment_cnt.to_string(),
+ ),
+ ("payment_connector", payment_connector.to_string()),
+ (
+ "currency",
+ payment_attempt
+ .currency
+ .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
+ ),
+ (
+ "payment_method",
+ payment_attempt.payment_method.map_or_else(
+ || "None".to_string(),
+ |payment_method| payment_method.to_string(),
+ ),
+ ),
+ (
+ "payment_method_type",
+ payment_attempt.payment_method_type.map_or_else(
+ || "None".to_string(),
+ |payment_method_type| payment_method_type.to_string(),
+ ),
+ ),
+ (
+ "capture_method",
+ payment_attempt.capture_method.map_or_else(
+ || "None".to_string(),
+ |capture_method| capture_method.to_string(),
+ ),
+ ),
+ (
+ "authentication_type",
+ payment_attempt.authentication_type.map_or_else(
+ || "None".to_string(),
+ |authentication_type| authentication_type.to_string(),
+ ),
+ ),
+ ("payment_status", payment_attempt.status.to_string()),
+ ),
+ );
+ logger::debug!("successfully pushed contract_based_routing metrics");
+
+ Ok(())
+ } else {
+ Ok(())
+ }
+}
+
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-fn get_desired_payment_status_for_success_routing_metrics(
+fn get_desired_payment_status_for_dynamic_routing_metrics(
attempt_status: common_enums::AttemptStatus,
) -> common_enums::AttemptStatus {
match attempt_status {
@@ -917,7 +1187,7 @@ fn get_desired_payment_status_for_success_routing_metrics(
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-fn get_success_based_metrics_outcome_for_payment(
+fn get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute: common_enums::AttemptStatus,
payment_connector: String,
first_success_based_connector: String,
@@ -957,7 +1227,6 @@ pub async fn disable_dynamic_routing_algorithm(
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
- let timestamp = common_utils::date_time::now_unix_timestamp();
let profile_id = business_profile.get_id().clone();
let (algorithm_id, dynamic_routing_algorithm, cache_entries_to_redact) =
match dynamic_routing_type {
@@ -988,14 +1257,12 @@ pub async fn disable_dynamic_routing_algorithm(
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: Some(routing_types::SuccessBasedAlgorithm {
algorithm_id_with_timestamp:
- routing_types::DynamicAlgorithmWithTimestamp {
- algorithm_id: None,
- timestamp,
- },
+ routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
}),
elimination_routing_algorithm: dynamic_routing_algo_ref
.elimination_routing_algorithm,
+ contract_based_routing: dynamic_routing_algo_ref.contract_based_routing,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
},
@@ -1033,13 +1300,49 @@ pub async fn disable_dynamic_routing_algorithm(
elimination_routing_algorithm: Some(
routing_types::EliminationRoutingAlgorithm {
algorithm_id_with_timestamp:
- routing_types::DynamicAlgorithmWithTimestamp {
- algorithm_id: None,
- timestamp,
- },
+ routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
},
),
+ contract_based_routing: dynamic_routing_algo_ref.contract_based_routing,
+ },
+ cache_entries_to_redact,
+ )
+ }
+ routing_types::DynamicRoutingType::ContractBasedRouting => {
+ let Some(algorithm_ref) = dynamic_routing_algo_ref.contract_based_routing else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Contract routing is already disabled".to_string(),
+ })?
+ };
+ let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
+ else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?
+ };
+ let cache_key = format!(
+ "{}_{}",
+ business_profile.get_id().get_string_repr(),
+ algorithm_id.get_string_repr()
+ );
+ let cache_entries_to_redact =
+ vec![cache::CacheKind::ContractBasedDynamicRoutingCache(
+ cache_key.into(),
+ )];
+ (
+ algorithm_id,
+ routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
+ elimination_routing_algorithm: dynamic_routing_algo_ref
+ .elimination_routing_algorithm,
+ dynamic_routing_volume_split: dynamic_routing_algo_ref
+ .dynamic_routing_volume_split,
+ contract_based_routing: Some(routing_types::ContractRoutingAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp::new(None),
+ enabled_feature: routing_types::DynamicRoutingFeatures::None,
+ }),
},
cache_entries_to_redact,
)
@@ -1088,15 +1391,18 @@ pub async fn enable_dynamic_routing_algorithm(
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
- let dynamic_routing = dynamic_routing_algo_ref.clone();
+ let mut dynamic_routing = dynamic_routing_algo_ref.clone();
match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
+ dynamic_routing
+ .disable_algorithm_id(routing_types::DynamicRoutingType::ContractBasedRouting);
+
enable_specific_routing_algorithm(
state,
key_store,
business_profile,
feature_to_enable,
- dynamic_routing_algo_ref,
+ dynamic_routing.clone(),
dynamic_routing_type,
dynamic_routing.success_based_algorithm,
)
@@ -1108,12 +1414,18 @@ pub async fn enable_dynamic_routing_algorithm(
key_store,
business_profile,
feature_to_enable,
- dynamic_routing_algo_ref,
+ dynamic_routing.clone(),
dynamic_routing_type,
dynamic_routing.elimination_routing_algorithm,
)
.await
}
+ routing_types::DynamicRoutingType::ContractBasedRouting => {
+ Err((errors::ApiErrorResponse::InvalidRequestData {
+ message: "Contract routing cannot be set as default".to_string(),
+ })
+ .into())
+ }
}
}
@@ -1128,7 +1440,7 @@ pub async fn enable_specific_routing_algorithm<A>(
algo_type: Option<A>,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>>
where
- A: routing_types::DynamicRoutingAlgoAccessor + Clone + std::fmt::Debug,
+ A: routing_types::DynamicRoutingAlgoAccessor + Clone + Debug,
{
// Algorithm wasn't created yet
let Some(mut algo_type) = algo_type else {
@@ -1169,9 +1481,8 @@ where
}
.into());
};
- *algo_type_enabled_features = feature_to_enable.clone();
- dynamic_routing_algo_ref
- .update_specific_ref(dynamic_routing_type.clone(), feature_to_enable.clone());
+ *algo_type_enabled_features = feature_to_enable;
+ dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable);
update_business_profile_active_dynamic_algorithm_ref(
db,
&state.into(),
@@ -1242,6 +1553,13 @@ pub async fn default_specific_dynamic_routing_setup(
algorithm_for: common_enums::TransactionType::Payment,
}
}
+
+ routing_types::DynamicRoutingType::ContractBasedRouting => {
+ return Err((errors::ApiErrorResponse::InvalidRequestData {
+ message: "Contract routing cannot be set as default".to_string(),
+ })
+ .into())
+ }
};
let record = db
@@ -1273,7 +1591,8 @@ pub async fn default_specific_dynamic_routing_setup(
Ok(ApplicationResponse::Json(new_record))
}
-pub struct SuccessBasedRoutingConfigParamsInterpolator {
+#[derive(Debug, Clone)]
+pub struct DynamicRoutingConfigParamsInterpolator {
pub payment_method: Option<common_enums::PaymentMethod>,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub authentication_type: Option<common_enums::AuthenticationType>,
@@ -1283,7 +1602,7 @@ pub struct SuccessBasedRoutingConfigParamsInterpolator {
pub card_bin: Option<String>,
}
-impl SuccessBasedRoutingConfigParamsInterpolator {
+impl DynamicRoutingConfigParamsInterpolator {
pub fn new(
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 7f7ea767108..c2363500c04 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1870,6 +1870,10 @@ impl Profile {
}),
)),
)
+ .service(
+ web::resource("/set_volume_split")
+ .route(web::post().to(routing::set_dynamic_routing_volume_split)),
+ )
.service(
web::scope("/elimination").service(
web::resource("/toggle")
@@ -1877,8 +1881,17 @@ impl Profile {
),
)
.service(
- web::resource("/set_volume_split")
- .route(web::post().to(routing::set_dynamic_routing_volume_split)),
+ web::scope("/contracts")
+ .service(web::resource("/toggle").route(
+ web::post().to(routing::contract_based_routing_setup_config),
+ ))
+ .service(web::resource("/config/{algorithm_id}").route(
+ web::patch().to(|state, req, path, payload| {
+ routing::contract_based_routing_update_configs(
+ state, req, path, payload,
+ )
+ }),
+ )),
),
);
}
diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs
index f3ba7076e53..c0f4062e15d 100644
--- a/crates/router/src/routes/metrics/bg_metrics_collector.rs
+++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs
@@ -14,6 +14,9 @@ pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>)
&cache::PM_FILTERS_CGRAPH_CACHE,
&cache::DECISION_MANAGER_CACHE,
&cache::SURCHARGE_CACHE,
+ &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
+ &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
+ &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
];
tokio::spawn(async move {
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index e7227e1f752..ac0f997a278 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -1130,7 +1130,7 @@ pub async fn toggle_success_based_routing(
pub async fn success_based_routing_update_configs(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<routing_types::SuccessBasedRoutingUpdateConfigQuery>,
+ path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>,
json_payload: web::Json<routing_types::SuccessBasedRoutingConfig>,
) -> impl Responder {
let flow = Flow::UpdateDynamicRoutingConfigs;
@@ -1165,6 +1165,100 @@ pub async fn success_based_routing_update_configs(
))
.await
}
+
+#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
+#[instrument(skip_all)]
+pub async fn contract_based_routing_setup_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<routing_types::ToggleDynamicRoutingPath>,
+ query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>,
+ json_payload: Option<web::Json<routing_types::ContractBasedRoutingConfig>>,
+) -> impl Responder {
+ let flow = Flow::ToggleDynamicRouting;
+ let routing_payload_wrapper = routing_types::ContractBasedRoutingSetupPayloadWrapper {
+ config: json_payload.map(|json| json.into_inner()),
+ profile_id: path.into_inner().profile_id,
+ features_to_enable: query.into_inner().enable,
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ routing_payload_wrapper.clone(),
+ |state,
+ auth: auth::AuthenticationData,
+ wrapper: routing_types::ContractBasedRoutingSetupPayloadWrapper,
+ _| async move {
+ Box::pin(routing::contract_based_dynamic_routing_setup(
+ state,
+ auth.key_store,
+ auth.merchant_account,
+ wrapper.profile_id,
+ wrapper.features_to_enable,
+ wrapper.config,
+ ))
+ .await
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: routing_payload_wrapper.profile_id,
+ required_permission: Permission::ProfileRoutingWrite,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
+#[instrument(skip_all)]
+pub async fn contract_based_routing_update_configs(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>,
+ json_payload: web::Json<routing_types::ContractBasedRoutingConfig>,
+) -> impl Responder {
+ let flow = Flow::UpdateDynamicRoutingConfigs;
+ let routing_payload_wrapper = routing_types::ContractBasedRoutingPayloadWrapper {
+ updated_config: json_payload.into_inner(),
+ algorithm_id: path.algorithm_id.clone(),
+ profile_id: path.profile_id.clone(),
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ routing_payload_wrapper.clone(),
+ |state,
+ auth: auth::AuthenticationData,
+ wrapper: routing_types::ContractBasedRoutingPayloadWrapper,
+ _| async {
+ Box::pin(routing::contract_based_routing_update_configs(
+ state,
+ wrapper.updated_config,
+ auth.merchant_account,
+ auth.key_store,
+ wrapper.algorithm_id,
+ wrapper.profile_id,
+ ))
+ .await
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: routing_payload_wrapper.profile_id,
+ required_permission: Permission::ProfileRoutingWrite,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn toggle_elimination_routing(
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 8302b5bf933..fb752e64b09 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -92,6 +92,16 @@ pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(||
)
});
+/// Contract Routing based Dynamic Algorithm Cache
+pub static CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
+ Cache::new(
+ "CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE",
+ CACHE_TTL,
+ CACHE_TTI,
+ Some(MAX_CAPACITY),
+ )
+});
+
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
@@ -113,6 +123,7 @@ pub enum CacheKind<'a> {
CGraph(Cow<'a, str>),
SuccessBasedDynamicRoutingCache(Cow<'a, str>),
EliminationBasedDynamicRoutingCache(Cow<'a, str>),
+ ContractBasedDynamicRoutingCache(Cow<'a, str>),
PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
}
@@ -128,6 +139,7 @@ impl CacheKind<'_> {
| CacheKind::CGraph(key)
| CacheKind::SuccessBasedDynamicRoutingCache(key)
| CacheKind::EliminationBasedDynamicRoutingCache(key)
+ | CacheKind::ContractBasedDynamicRoutingCache(key)
| CacheKind::PmFiltersCGraph(key)
| CacheKind::All(key) => key,
}
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 373ac370e2f..28b76148765 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -6,8 +6,9 @@ use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE,
- DECISION_MANAGER_CACHE, ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE,
- ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
+ CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE,
+ ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE,
+ SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
@@ -147,6 +148,15 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
.await;
key
}
+ CacheKind::ContractBasedDynamicRoutingCache(key) => {
+ CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: message.tenant.clone(),
+ })
+ .await;
+ key
+ }
CacheKind::SuccessBasedDynamicRoutingCache(key) => {
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
@@ -220,6 +230,12 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
prefix: message.tenant.clone(),
})
.await;
+ CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: message.tenant.clone(),
+ })
+ .await;
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
diff --git a/proto/contract_routing.proto b/proto/contract_routing.proto
new file mode 100644
index 00000000000..6b842e3096e
--- /dev/null
+++ b/proto/contract_routing.proto
@@ -0,0 +1,76 @@
+syntax = "proto3";
+package contract_routing;
+
+service ContractScoreCalculator {
+ rpc FetchContractScore (CalContractScoreRequest) returns (CalContractScoreResponse);
+
+ rpc UpdateContract (UpdateContractRequest) returns (UpdateContractResponse);
+
+ rpc InvalidateContract (InvalidateContractRequest) returns (InvalidateContractResponse);
+}
+
+// API-1 types
+message CalContractScoreRequest {
+ string id = 1;
+ string params = 2;
+ repeated string labels = 3;
+ CalContractScoreConfig config = 4;
+}
+
+message CalContractScoreConfig {
+ repeated double constants = 1;
+ TimeScale time_scale = 2;
+}
+
+message TimeScale {
+ enum Scale {
+ Day = 0;
+ Month = 1;
+ }
+ Scale time_scale = 1;
+}
+
+message CalContractScoreResponse {
+ repeated ScoreData labels_with_score = 1;
+}
+
+message ScoreData {
+ double score = 1;
+ string label = 2;
+ uint64 current_count = 3;
+}
+
+// API-2 types
+message UpdateContractRequest {
+ string id = 1;
+ string params = 2;
+ repeated LabelInformation labels_information = 3;
+}
+
+message LabelInformation {
+ string label = 1;
+ uint64 target_count = 2;
+ uint64 target_time = 3;
+ uint64 current_count = 4;
+}
+
+message UpdateContractResponse {
+ enum UpdationStatus {
+ CONTRACT_UPDATION_SUCCEEDED = 0;
+ CONTRACT_UPDATION_FAILED = 1;
+ }
+ UpdationStatus status = 1;
+}
+
+// API-3 types
+message InvalidateContractRequest {
+ string id = 1;
+}
+
+message InvalidateContractResponse {
+ enum InvalidationStatus {
+ CONTRACT_INVALIDATION_SUCCEEDED = 0;
+ CONTRACT_INVALIDATION_FAILED = 1;
+ }
+ InvalidationStatus status = 1;
+}
\ No newline at end of file
|
feat
|
Contract based routing integration (#6761)
|
ead568e5920e1f85396d029f22dc6e65c74c41b5
|
2023-01-23 13:28:18
|
Nishant Joshi
|
doc: minor formatting and logo changes in github README (#457)
| false
|
diff --git a/README.md b/README.md
index ca05e0f9ca3..b5e8e9438ae 100644
--- a/README.md
+++ b/README.md
@@ -1,47 +1,54 @@
-# HyperSwitch
-
-[![Build Status][actions-badge]][actions-url]
-[![Apache 2.0 license][license-badge]][license-url]
-
-[actions-badge]: https://github.com/juspay/hyperswitch/workflows/CI/badge.svg
-[actions-url]: https://github.com/juspay/hyperswitch/actions?query=workflow%3ACI+branch%3Amain
-[license-badge]: https://img.shields.io/github/license/juspay/hyperswitch
-[license-url]: https://github.com/juspay/hyperswitch/blob/main/LICENSE
-
-HyperSwitch is an **Open Source Financial Switch** to make payments Fast,
-Reliable and Affordable.
-It lets you connect with **multiple payment processors with a single API
-integration**.
-Once integrated, you can add new payment processors and route traffic
-effortlessly.
-Using HyperSwitch, you can:
+<p align="center">
+ <img src="./docs/imgs/hyperswitch-logo-dark.svg#gh-dark-mode-only" alt="HyperSwitch-Logo" width="40%" />
+ <img src="./docs/imgs/hyperswitch-logo-light.svg#gh-light-mode-only" alt="HyperSwitch-Logo" width="40%" />
+</p>
-- **Reduce dependency** on a single processor like Stripe or Braintree
-- **Reduce Dev efforts** by 90% in adding & maintaining integrations
-- **Improve success rates** with auto-retries
-- **Reduce processing fees** through smart routing
-- **Customize your payment** flow with 100% visibility and control
-- **Increase business reach** with local payment methods
-- **Embrace diversity** in payments
+<p align="center">
+<i>Unified Payments Switch. Fast. Reliable. Affordable.</i>
+</p>
-_HyperSwitch is wire-compatible with top processors like Stripe making it easy
-to integrate._
+<p align="center">
+ <a href="https://github.com/juspay/hyperswitch/actions?query=workflow%3ACI+branch%3Amain">
+ <img src="https://github.com/juspay/hyperswitch/workflows/CI/badge.svg" />
+ </a>
+ <a href="https://github.com/juspay/hyperswitch/blob/main/LICENSE">
+ <img src="https://img.shields.io/github/license/juspay/hyperswitch" />
+ </a>
+</p>
<p align="center">
-<img src= "./docs/imgs/hyperswitch-product.png" alt="HyperSwitch-Product" width="60%" />
+ <a href="#quick-start-guide">Quick Start Guide</a> •
+ <a href="#fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> •
+ <a href="#supported-features">Supported Features</a> •
+ <a href="#faqs">FAQs</a>
+ <br>
+ <a href="#whats-included">What's Included</a> •
+ <a href="#join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> •
+ <a href="#community">Community</a> •
+ <a href="#bugs-and-feature-requests">Bugs and feature requests</a> •
+ <a href="#versioning">Versioning</a> •
+ <a href="#copyright-and-license">Copyright and License</a>
</p>
+<hr>
-## Table of Contents
+HyperSwitch is an Open Source Financial Switch to make payments **Fast, Reliable
+and Affordable**.
+It lets you connect with multiple payment processors and route traffic
+effortlessly, all with a single API integration.
+Using HyperSwitch, you can:
+
+- **Reduce dependency** on a single processor like Stripe or Braintree
+- **Reduce Dev effort** by 90% to add & maintain integrations
+- **Improve success rates** with seamless failover and auto-retries
+- **Reduce processing fees** with smart routing
+- **Customize payment flows** with full visibility and control
+- **Increase business reach** with local / alternate payment methods
+
+> HyperSwitch is **wire-compatible** with top processors like Stripe, making it
+> easy to integrate.
-- [Quick Start Guide](#quick-start-guide)
-- [Fast Integration for Stripe Users](#fast-integration-for-stripe-users)
-- [Supported Features](#supported-features)
-- [What's Included](#whats-included)
-- [Join us in building HyperSwitch](#join-us-in-building-hyperswitch)
-- [Community](#community)
-- [Bugs and feature requests](#bugs-and-feature-requests)
-- [Versioning](#versioning)
-- [Copyright and License](#copyright-and-license)
+<br>
+<img src="./docs/imgs/hyperswitch-product.png" alt="HyperSwitch-Product" width="50%" />
## Quick Start Guide
@@ -50,7 +57,8 @@ You have three options to try out HyperSwitch:
1. [Try it in our Sandbox Environment](/docs/try_sandbox.md): Fast and easy to
start.
No code or setup required in your system.
-2. Try our React Demo App: A simple demo of integrating Hyperswitch with your React app.
+2. Try our React Demo App: A simple demo of integrating Hyperswitch with your
+ React app.
<a href="https://github.com/aashu331998/hyperswitch-react-demo-app/archive/refs/heads/main.zip">
<img src= "./docs/imgs/download-button.png" alt="Download Now" width="190rem" />
@@ -118,6 +126,13 @@ analytics, and operations end-to-end:
You can [try the hosted version in our sandbox][dashboard].
+## FAQs
+
+Got more more questions?
+Please refer to our [FAQs page][faqs].
+
+[faqs]: https://hyperswitch.io/docs/websiteFAQ
+
<!--
## Documentation
@@ -174,8 +189,8 @@ should be introduced checking it agrees with actual structure -->
### Our Belief
-_We believe payments should be open, fast, reliable and affordable to serve
-billions of people at scale._
+> Payments should be open, fast, reliable and affordable to serve
+> the billions of people at scale.
<!--
HyperSwitch would allow everyone to quickly customize and set up an open payment
@@ -187,23 +202,25 @@ It was born from our struggle to understand and integrate various payment
options/payment processors/networks and banks, with varying degrees of
documentation and inconsistent API semantics. -->
-Globally payment diversity has been growing exponentially.
-There are hundreds of payment processors and new payment methods.
-So, businesses embrace diversity by onboarding multiple payment processors to
-increase conversion, reduce cost and improve control.
-But integrating and maintaining multiple processors needs a lot of dev efforts.
-So, why should devs across companies repeat this same work?
+Globally payment diversity has been growing at a rapid pace.
+There are hundreds of payment processors and new payment methods like BNPL,
+RTP etc.
+Businesses need to embrace this diversity to increase conversion, reduce cost
+and improve control.
+But integrating and maintaining multiple processors needs a lot of dev effort.
+Why should devs across companies repeat the same work?
Why can't it be unified and reused? Hence, HyperSwitch was born to create that
-reusable core and let companies build or customize on top of it.
+reusable core and let companies build and customize on top of it.
### Our Values
-1. Embrace Diversity of Payments: It leads to a better experience, efficiency &
- resilience.
-2. Future is Open Source: It enables Innovation, code reuse & affordability.
-3. Be part of the Community: It helps in collaboration, learning & contribution.
-4. Build it like a System Software: It makes the product reliable, secure &
- performant.
+1. Embrace Payments Diversity: It will drive innovation in the ecosystem in
+ multiple ways.
+2. Make it Open Source: Increases trust; Improves the quality and reusability of
+ software.
+3. Be Community driven: It enables participatory design and development.
+4. Build it like Systems Software: This sets a high bar for Reliability,
+ Security and Performance SLAs.
5. Maximize Value Creation: For developers, customers & partners.
### Contributing
diff --git a/docs/imgs/hyperswitch-logo-dark.svg b/docs/imgs/hyperswitch-logo-dark.svg
new file mode 100644
index 00000000000..fbf0d89d410
--- /dev/null
+++ b/docs/imgs/hyperswitch-logo-dark.svg
@@ -0,0 +1,29 @@
+<svg width="766" height="100" viewBox="0 0 766 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_1969_1952)">
+<path d="M370.801 53.4399C370.801 70.0799 360.581 79.9999 346.441 79.9999C338.621 79.9999 331.811 76.7899 328.701 71.4799V99.0399H317.771V27.6899H327.791L328.691 35.5099C331.801 30.1999 338.411 26.6899 346.431 26.6899C360.061 26.6899 370.791 36.2099 370.791 53.4499L370.801 53.4399ZM359.471 53.4399C359.471 42.9199 353.261 36.3999 344.231 36.3999C335.611 36.2999 329.001 42.9099 329.001 53.5399C329.001 64.1699 335.621 70.2799 344.231 70.2799C352.841 70.2799 359.471 63.9699 359.471 53.4399Z" fill="white"/>
+<path d="M428.931 56.3498H389.641C389.841 65.9698 396.151 70.9798 404.171 70.9798C410.181 70.9798 415.201 68.1698 417.301 62.5598H428.431C425.721 72.9798 416.501 79.9998 403.971 79.9998C388.631 79.9998 378.511 69.3798 378.511 53.2398C378.511 37.0998 388.631 26.5798 403.871 26.5798C419.111 26.5798 428.931 36.7998 428.931 52.2398V56.3498ZM389.741 48.7298H417.801C417.201 39.8098 411.291 35.2998 403.871 35.2998C396.451 35.2998 390.541 39.8098 389.741 48.7298Z" fill="white"/>
+<path d="M448.281 27.6899C443.181 27.6899 439.051 31.8199 439.051 36.9199V79.0099H450.081V51.6499V39.8199C450.081 38.5499 451.111 37.5099 452.391 37.5099H469.231V27.6899H448.291H448.281Z" fill="white"/>
+<path d="M300.14 27.5898L286.01 70.1898L270.77 27.6898H258.94L278.48 78.3098C279.08 79.9098 279.38 81.2198 279.38 82.5198C279.38 83.2298 279.31 83.8798 279.19 84.4798L279.16 84.5898C279.09 84.9098 279.01 85.2098 278.91 85.4998L278.17 88.2098C277.99 88.8798 277.38 89.3398 276.69 89.3398H261.14V99.0598H272.47C280.09 99.0598 286.4 97.2598 290.01 87.2298L311.56 27.6898L300.13 27.5898H300.14Z" fill="white"/>
+<path d="M206.82 78.9999H217.74V51.3399C217.74 42.7199 222.45 36.7099 231.17 36.7099C238.79 36.6099 243.5 41.1199 243.5 51.0399V78.9999H254.43V49.3299C254.43 31.7899 243.71 26.5799 233.98 26.5799C226.56 26.5799 220.75 29.4899 217.74 34.2999V6.63989H206.82V78.9999Z" fill="white"/>
+<path d="M483.66 63.4699C483.76 68.7799 488.67 71.8899 495.39 71.8899C502.11 71.8899 506.11 69.3799 506.11 64.8699C506.11 60.9599 504.11 58.8599 498.29 57.9499L487.97 56.1499C477.95 54.4499 474.04 49.2299 474.04 41.9199C474.04 32.6999 483.16 26.6899 494.79 26.6899C507.32 26.6899 516.44 32.6999 516.54 42.9299H505.72C505.62 37.7199 501.11 34.8099 494.8 34.8099C488.49 34.8099 484.98 37.3199 484.98 41.5299C484.98 45.2399 487.59 46.9399 493.3 47.9399L503.42 49.7399C512.94 51.4399 517.35 56.1499 517.35 63.8699C517.35 74.4899 507.53 80.0099 495.6 80.0099C482.07 80.0099 472.95 73.4999 472.75 63.4699H483.68H483.66Z" fill="white"/>
+<path d="M542.19 66.9799L553.82 27.6899H565.25L576.68 66.9799L586.4 27.6899H597.93L583.4 79.0099H571.07L559.44 39.9199L547.71 79.0099H535.28L520.65 27.6899H532.18L542.2 66.9799H542.19Z" fill="white"/>
+<path d="M604.34 6.63989H616.47V18.0699H604.34V6.63989ZM604.94 27.6899H615.86V79.0099H604.94V27.6899Z" fill="white"/>
+<path d="M685.32 36.1099C676.8 36.1099 670.99 42.3199 670.99 53.2499C670.99 64.7799 677 70.3899 685.02 70.3899C691.43 70.3899 696.15 66.7799 698.25 59.9699H709.88C707.27 72.3999 697.85 80.0199 685.22 80.0199C669.99 80.0199 659.76 69.3998 659.76 53.2599C659.76 37.1199 669.98 26.5999 685.32 26.5999C697.85 26.5999 707.17 33.7199 709.88 46.1399H698.05C696.25 39.7299 691.33 36.1199 685.32 36.1199V36.1099Z" fill="white"/>
+<path d="M642.87 69.2799C642.23 69.2799 641.72 68.7599 641.72 68.1299V37.41H653.65V27.69H641.72V13.95H630.8V22.87C630.8 26.08 629.8 27.68 626.59 27.68H622.18V37.4H630.8V65.0599C630.8 73.9799 635.71 78.99 644.63 78.99H653.55V69.2699H642.88L642.87 69.2799Z" fill="white"/>
+<path d="M745.22 26.5799C737.8 26.5799 731.99 29.4899 728.98 34.2999V6.63989H718.06V78.9999H728.98V51.3399C728.98 42.7199 733.69 36.7099 742.41 36.7099C750.03 36.6099 754.74 41.1199 754.74 51.0399V78.9999H765.67V49.3299C765.67 31.7899 754.95 26.5799 745.22 26.5799Z" fill="white"/>
+<g clip-path="url(#clip1_1969_1952)">
+<path d="M135.792 0H42.875C19.1958 0 0 19.1958 0 42.875C0 66.5542 19.1958 85.75 42.875 85.75H135.792C159.471 85.75 178.667 66.5542 178.667 42.875C178.667 19.1958 159.471 0 135.792 0Z" fill="#006DF9"/>
+<path d="M140.261 56.4367C147.751 56.4367 153.822 50.3649 153.822 42.8751C153.822 35.3852 147.751 29.3135 140.261 29.3135C132.771 29.3135 126.699 35.3852 126.699 42.8751C126.699 50.3649 132.771 56.4367 140.261 56.4367Z" fill="white"/>
+<path d="M53.2718 53.4511L39.0877 31.4253C38.7683 30.9299 38.0448 30.9299 37.7254 31.4253L23.5413 53.4511C23.1925 53.9888 23.5804 54.6993 24.2224 54.6993H52.5907C53.2327 54.6993 53.6206 53.9888 53.2718 53.4511Z" fill="white"/>
+<path d="M100.55 30.353H78.1172C77.3972 30.353 76.8135 30.9367 76.8135 31.6567V54.0899C76.8135 54.8099 77.3972 55.3936 78.1172 55.3936H100.55C101.27 55.3936 101.854 54.8099 101.854 54.0899V31.6567C101.854 30.9367 101.27 30.353 100.55 30.353Z" fill="white"/>
+</g>
+</g>
+<defs>
+<clipPath id="clip0_1969_1952">
+<rect width="765.66" height="99.05" fill="white"/>
+</clipPath>
+<clipPath id="clip1_1969_1952">
+<rect width="178.667" height="85.75" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/docs/imgs/hyperswitch-logo-light.svg b/docs/imgs/hyperswitch-logo-light.svg
new file mode 100644
index 00000000000..c951a909dd4
--- /dev/null
+++ b/docs/imgs/hyperswitch-logo-light.svg
@@ -0,0 +1,29 @@
+<svg width="766" height="100" viewBox="0 0 766 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_1969_1952)">
+<path d="M370.801 53.4399C370.801 70.0799 360.581 79.9999 346.441 79.9999C338.621 79.9999 331.811 76.7899 328.701 71.4799V99.0399H317.771V27.6899H327.791L328.691 35.5099C331.801 30.1999 338.411 26.6899 346.431 26.6899C360.061 26.6899 370.791 36.2099 370.791 53.4499L370.801 53.4399ZM359.471 53.4399C359.471 42.9199 353.261 36.3999 344.231 36.3999C335.611 36.2999 329.001 42.9099 329.001 53.5399C329.001 64.1699 335.621 70.2799 344.231 70.2799C352.841 70.2799 359.471 63.9699 359.471 53.4399Z" fill="#242628"/>
+<path d="M428.931 56.3498H389.641C389.841 65.9698 396.151 70.9798 404.171 70.9798C410.181 70.9798 415.201 68.1698 417.301 62.5598H428.431C425.721 72.9798 416.501 79.9998 403.971 79.9998C388.631 79.9998 378.511 69.3798 378.511 53.2398C378.511 37.0998 388.631 26.5798 403.871 26.5798C419.111 26.5798 428.931 36.7998 428.931 52.2398V56.3498ZM389.741 48.7298H417.801C417.201 39.8098 411.291 35.2998 403.871 35.2998C396.451 35.2998 390.541 39.8098 389.741 48.7298Z" fill="#242628"/>
+<path d="M448.281 27.6899C443.181 27.6899 439.051 31.8199 439.051 36.9199V79.0099H450.081V51.6499V39.8199C450.081 38.5499 451.111 37.5099 452.391 37.5099H469.231V27.6899H448.291H448.281Z" fill="#242628"/>
+<path d="M300.14 27.5898L286.01 70.1898L270.77 27.6898H258.94L278.48 78.3098C279.08 79.9098 279.38 81.2198 279.38 82.5198C279.38 83.2298 279.31 83.8798 279.19 84.4798L279.16 84.5898C279.09 84.9098 279.01 85.2098 278.91 85.4998L278.17 88.2098C277.99 88.8798 277.38 89.3398 276.69 89.3398H261.14V99.0598H272.47C280.09 99.0598 286.4 97.2598 290.01 87.2298L311.56 27.6898L300.13 27.5898H300.14Z" fill="#242628"/>
+<path d="M206.82 78.9999H217.74V51.3399C217.74 42.7199 222.45 36.7099 231.17 36.7099C238.79 36.6099 243.5 41.1199 243.5 51.0399V78.9999H254.43V49.3299C254.43 31.7899 243.71 26.5799 233.98 26.5799C226.56 26.5799 220.75 29.4899 217.74 34.2999V6.63989H206.82V78.9999Z" fill="#242628"/>
+<path d="M483.66 63.4699C483.76 68.7799 488.67 71.8899 495.39 71.8899C502.11 71.8899 506.11 69.3799 506.11 64.8699C506.11 60.9599 504.11 58.8599 498.29 57.9499L487.97 56.1499C477.95 54.4499 474.04 49.2299 474.04 41.9199C474.04 32.6999 483.16 26.6899 494.79 26.6899C507.32 26.6899 516.44 32.6999 516.54 42.9299H505.72C505.62 37.7199 501.11 34.8099 494.8 34.8099C488.49 34.8099 484.98 37.3199 484.98 41.5299C484.98 45.2399 487.59 46.9399 493.3 47.9399L503.42 49.7399C512.94 51.4399 517.35 56.1499 517.35 63.8699C517.35 74.4899 507.53 80.0099 495.6 80.0099C482.07 80.0099 472.95 73.4999 472.75 63.4699H483.68H483.66Z" fill="#242628"/>
+<path d="M542.19 66.9799L553.82 27.6899H565.25L576.68 66.9799L586.4 27.6899H597.93L583.4 79.0099H571.07L559.44 39.9199L547.71 79.0099H535.28L520.65 27.6899H532.18L542.2 66.9799H542.19Z" fill="#242628"/>
+<path d="M604.34 6.63989H616.47V18.0699H604.34V6.63989ZM604.94 27.6899H615.86V79.0099H604.94V27.6899Z" fill="#242628"/>
+<path d="M685.32 36.1099C676.8 36.1099 670.99 42.3199 670.99 53.2499C670.99 64.7799 677 70.3899 685.02 70.3899C691.43 70.3899 696.15 66.7799 698.25 59.9699H709.88C707.27 72.3999 697.85 80.0199 685.22 80.0199C669.99 80.0199 659.76 69.3998 659.76 53.2599C659.76 37.1199 669.98 26.5999 685.32 26.5999C697.85 26.5999 707.17 33.7199 709.88 46.1399H698.05C696.25 39.7299 691.33 36.1199 685.32 36.1199V36.1099Z" fill="#242628"/>
+<path d="M642.87 69.2799C642.23 69.2799 641.72 68.7599 641.72 68.1299V37.41H653.65V27.69H641.72V13.95H630.8V22.87C630.8 26.08 629.8 27.68 626.59 27.68H622.18V37.4H630.8V65.0599C630.8 73.9799 635.71 78.99 644.63 78.99H653.55V69.2699H642.88L642.87 69.2799Z" fill="#242628"/>
+<path d="M745.22 26.5799C737.8 26.5799 731.99 29.4899 728.98 34.2999V6.63989H718.06V78.9999H728.98V51.3399C728.98 42.7199 733.69 36.7099 742.41 36.7099C750.03 36.6099 754.74 41.1199 754.74 51.0399V78.9999H765.67V49.3299C765.67 31.7899 754.95 26.5799 745.22 26.5799Z" fill="#242628"/>
+<g clip-path="url(#clip1_1969_1952)">
+<path d="M135.792 0H42.875C19.1958 0 0 19.1958 0 42.875C0 66.5542 19.1958 85.75 42.875 85.75H135.792C159.471 85.75 178.667 66.5542 178.667 42.875C178.667 19.1958 159.471 0 135.792 0Z" fill="#006DF9"/>
+<path d="M140.261 56.4367C147.751 56.4367 153.822 50.3649 153.822 42.8751C153.822 35.3852 147.751 29.3135 140.261 29.3135C132.771 29.3135 126.699 35.3852 126.699 42.8751C126.699 50.3649 132.771 56.4367 140.261 56.4367Z" fill="white"/>
+<path d="M53.2718 53.4511L39.0877 31.4253C38.7683 30.9299 38.0448 30.9299 37.7254 31.4253L23.5413 53.4511C23.1925 53.9888 23.5804 54.6993 24.2224 54.6993H52.5907C53.2327 54.6993 53.6206 53.9888 53.2718 53.4511Z" fill="white"/>
+<path d="M100.55 30.353H78.1172C77.3972 30.353 76.8135 30.9367 76.8135 31.6567V54.0899C76.8135 54.8099 77.3972 55.3936 78.1172 55.3936H100.55C101.27 55.3936 101.854 54.8099 101.854 54.0899V31.6567C101.854 30.9367 101.27 30.353 100.55 30.353Z" fill="white"/>
+</g>
+</g>
+<defs>
+<clipPath id="clip0_1969_1952">
+<rect width="765.66" height="99.05" fill="white"/>
+</clipPath>
+<clipPath id="clip1_1969_1952">
+<rect width="178.667" height="85.75" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/docs/imgs/hyperswitch-product.png b/docs/imgs/hyperswitch-product.png
index 87b204b3400..ad1c6c1ed03 100644
Binary files a/docs/imgs/hyperswitch-product.png and b/docs/imgs/hyperswitch-product.png differ
|
doc
|
minor formatting and logo changes in github README (#457)
|
279961e1699ea367ab51eb3c0e39ef8359bceae8
|
2022-12-23 19:28:06
|
Sangamesh Kulkarni
|
refactor: attempt and intent status (#210)
| false
|
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 8e1c71c2279..f915cda5177 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -15,9 +15,9 @@
pub enum AttemptStatus {
Started,
AuthenticationFailed,
- JuspayDeclined,
- PendingVbv,
- VbvSuccessful,
+ RouterDeclined,
+ AuthenticationPending,
+ AuthenticationSuccessful,
Authorized,
AuthorizationFailed,
Charged,
@@ -506,11 +506,11 @@ impl From<AttemptStatus> for IntentStatus {
AttemptStatus::PaymentMethodAwaited => IntentStatus::RequiresPaymentMethod,
AttemptStatus::Authorized => IntentStatus::RequiresCapture,
- AttemptStatus::PendingVbv => IntentStatus::RequiresCustomerAction,
+ AttemptStatus::AuthenticationPending => IntentStatus::RequiresCustomerAction,
AttemptStatus::PartialCharged
| AttemptStatus::Started
- | AttemptStatus::VbvSuccessful
+ | AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::VoidInitiated
@@ -520,7 +520,7 @@ impl From<AttemptStatus> for IntentStatus {
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::VoidFailed
- | AttemptStatus::JuspayDeclined
+ | AttemptStatus::RouterDeclined
| AttemptStatus::CaptureFailed
| AttemptStatus::Failure => IntentStatus::Failed,
AttemptStatus::Voided => IntentStatus::Cancelled,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 4474f2437d4..815b1f98c77 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -471,7 +471,7 @@ pub fn get_redirection_response(
"Authorised" => storage_enums::AttemptStatus::Charged,
"Refused" => storage_enums::AttemptStatus::Failure,
"Cancelled" => storage_enums::AttemptStatus::Failure,
- "RedirectShopper" => storage_enums::AttemptStatus::PendingVbv,
+ "RedirectShopper" => storage_enums::AttemptStatus::AuthenticationPending,
_ => storage_enums::AttemptStatus::Pending,
};
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index c0aede0a29c..0b625e9a585 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -486,7 +486,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, &ActionResponse>>
impl From<CheckoutRedirectResponseStatus> for enums::AttemptStatus {
fn from(item: CheckoutRedirectResponseStatus) -> Self {
match item {
- CheckoutRedirectResponseStatus::Success => Self::VbvSuccessful,
+ CheckoutRedirectResponseStatus::Success => Self::AuthenticationSuccessful,
CheckoutRedirectResponseStatus::Failure => Self::Failure,
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index d74609c0d46..204726a87ef 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -309,7 +309,7 @@ impl From<StripePaymentStatus> for enums::AttemptStatus {
StripePaymentStatus::Succeeded => Self::Charged,
StripePaymentStatus::Failed => Self::Failure,
StripePaymentStatus::Processing => Self::Authorizing,
- StripePaymentStatus::RequiresCustomerAction => Self::PendingVbv,
+ StripePaymentStatus::RequiresCustomerAction => Self::AuthenticationPending,
StripePaymentStatus::RequiresPaymentMethod => Self::PaymentMethodAwaited,
StripePaymentStatus::RequiresConfirmation => Self::ConfirmationAwaited,
StripePaymentStatus::Canceled => Self::Voided,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index d84db938770..93cd443a71c 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -273,7 +273,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
),
_ => (
enums::IntentStatus::RequiresCustomerAction,
- enums::AttemptStatus::PendingVbv,
+ enums::AttemptStatus::AuthenticationPending,
),
};
diff --git a/crates/router/src/scheduler/workflows/payment_sync.rs b/crates/router/src/scheduler/workflows/payment_sync.rs
index 48824d6d367..6f63d738af9 100644
--- a/crates/router/src/scheduler/workflows/payment_sync.rs
+++ b/crates/router/src/scheduler/workflows/payment_sync.rs
@@ -47,7 +47,7 @@ impl ProcessTrackerWorkflow for PaymentsSyncWorkflow {
.await?;
let terminal_status = vec![
- enums::AttemptStatus::JuspayDeclined,
+ enums::AttemptStatus::RouterDeclined,
enums::AttemptStatus::Charged,
enums::AttemptStatus::AutoRefunded,
enums::AttemptStatus::Voided,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 99a930a6dbc..70d892ee527 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -187,13 +187,13 @@ impl From<F<storage_enums::AttemptStatus>> for F<storage_enums::IntentStatus> {
storage_enums::AttemptStatus::Authorized => {
storage_enums::IntentStatus::RequiresCapture
}
- storage_enums::AttemptStatus::PendingVbv => {
+ storage_enums::AttemptStatus::AuthenticationPending => {
storage_enums::IntentStatus::RequiresCustomerAction
}
storage_enums::AttemptStatus::PartialCharged
| storage_enums::AttemptStatus::Started
- | storage_enums::AttemptStatus::VbvSuccessful
+ | storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::VoidInitiated
@@ -203,7 +203,7 @@ impl From<F<storage_enums::AttemptStatus>> for F<storage_enums::IntentStatus> {
storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::VoidFailed
- | storage_enums::AttemptStatus::JuspayDeclined
+ | storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::CaptureFailed
| storage_enums::AttemptStatus::Failure => storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Voided => storage_enums::IntentStatus::Cancelled,
diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs
index 5786b61fc7f..eb4d4a200af 100644
--- a/crates/storage_models/src/enums.rs
+++ b/crates/storage_models/src/enums.rs
@@ -33,9 +33,9 @@ pub mod diesel_exports {
pub enum AttemptStatus {
Started,
AuthenticationFailed,
- JuspayDeclined,
- PendingVbv,
- VbvSuccessful,
+ RouterDeclined,
+ AuthenticationPending,
+ AuthenticationSuccessful,
Authorized,
AuthorizationFailed,
Charged,
diff --git a/migrations/2022-12-22-091431_attempt_status_rename/down.sql b/migrations/2022-12-22-091431_attempt_status_rename/down.sql
new file mode 100644
index 00000000000..8c0949326b4
--- /dev/null
+++ b/migrations/2022-12-22-091431_attempt_status_rename/down.sql
@@ -0,0 +1,3 @@
+ALTER TYPE "AttemptStatus" RENAME VALUE 'router_declined' TO 'juspay_declined';
+ALTER TYPE "AttemptStatus" RENAME VALUE 'authentication_successful' TO 'pending_vbv';
+ALTER TYPE "AttemptStatus" RENAME VALUE 'authentication_pending' TO 'vbv_successful';
diff --git a/migrations/2022-12-22-091431_attempt_status_rename/up.sql b/migrations/2022-12-22-091431_attempt_status_rename/up.sql
new file mode 100644
index 00000000000..ec3a9aa0698
--- /dev/null
+++ b/migrations/2022-12-22-091431_attempt_status_rename/up.sql
@@ -0,0 +1,3 @@
+ALTER TYPE "AttemptStatus" RENAME VALUE 'juspay_declined' TO 'router_declined';
+ALTER TYPE "AttemptStatus" RENAME VALUE 'pending_vbv' TO 'authentication_successful';
+ALTER TYPE "AttemptStatus" RENAME VALUE 'vbv_successful' TO 'authentication_pending';
|
refactor
|
attempt and intent status (#210)
|
1ea823b0488c783315da156a474dedce2556d334
|
2023-09-18 17:35:04
|
Hrithikesh
|
refactor: remove redundant validate_capture_method call (#2171)
| false
|
diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index 75553b4ee2b..d9aa340b1dc 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -175,7 +175,6 @@ impl
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs
index 5e13bf31a97..b5d23410ce5 100644
--- a/crates/router/src/connector/aci.rs
+++ b/crates/router/src/connector/aci.rs
@@ -298,7 +298,6 @@ impl
>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 9da548baf24..64cba7410eb 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -610,7 +610,6 @@ impl
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
check_for_payment_method_balance(req)?;
Ok(Some(
services::RequestBuilder::new()
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index 8f3cf8efeb4..f7086cfb7ad 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -259,7 +259,6 @@ impl
req: &types::PaymentsInitRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 44eee1e1811..c40317ea376 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -330,7 +330,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index a8f660bb738..a8ea787eaf4 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -449,7 +449,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs
index 52fd574b381..471cab7199f 100644
--- a/crates/router/src/connector/bitpay.rs
+++ b/crates/router/src/connector/bitpay.rs
@@ -180,7 +180,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs
index feb45ac6927..04206dd80e5 100644
--- a/crates/router/src/connector/bluesnap.rs
+++ b/crates/router/src/connector/bluesnap.rs
@@ -611,7 +611,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/boku.rs b/crates/router/src/connector/boku.rs
index 70c296c4343..65e962f5aa0 100644
--- a/crates/router/src/connector/boku.rs
+++ b/crates/router/src/connector/boku.rs
@@ -217,7 +217,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 8e4e1b03caa..1dddc876c14 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -728,7 +728,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs
index 497470ecf23..a185c6a653b 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/router/src/connector/cashtocode.rs
@@ -213,7 +213,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index 9d7afb0ccbf..332de31330d 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -501,7 +501,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs
index f1abe79ee02..463a8e679a1 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/router/src/connector/coinbase.rs
@@ -194,7 +194,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index 2feb5089abf..2ee645a2770 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -225,7 +225,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index 1efda3fc149..26fd156abe8 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -478,7 +478,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs
index 17990792059..2e18030ff4f 100644
--- a/crates/router/src/connector/dlocal.rs
+++ b/crates/router/src/connector/dlocal.rs
@@ -217,7 +217,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs
index 8f3f3181012..4c7fc6c4347 100644
--- a/crates/router/src/connector/dummyconnector.rs
+++ b/crates/router/src/connector/dummyconnector.rs
@@ -199,7 +199,6 @@ impl<const T: u8>
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs
index 2a4093a24aa..83bbf592f80 100644
--- a/crates/router/src/connector/fiserv.rs
+++ b/crates/router/src/connector/fiserv.rs
@@ -515,7 +515,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
let request = Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs
index f94b2c4945b..ecb63bcd752 100644
--- a/crates/router/src/connector/forte.rs
+++ b/crates/router/src/connector/forte.rs
@@ -211,7 +211,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs
index de0470be2e4..8d803913c4a 100644
--- a/crates/router/src/connector/globalpay.rs
+++ b/crates/router/src/connector/globalpay.rs
@@ -639,7 +639,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/globepay.rs b/crates/router/src/connector/globepay.rs
index 68b8e8b67e3..e0bb9e1fd3f 100644
--- a/crates/router/src/connector/globepay.rs
+++ b/crates/router/src/connector/globepay.rs
@@ -198,7 +198,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Put)
diff --git a/crates/router/src/connector/helcim.rs b/crates/router/src/connector/helcim.rs
index a6bec7bacd9..e5444b53be0 100644
--- a/crates/router/src/connector/helcim.rs
+++ b/crates/router/src/connector/helcim.rs
@@ -174,7 +174,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs
index ebdba849163..f55ee22a23b 100644
--- a/crates/router/src/connector/iatapay.rs
+++ b/crates/router/src/connector/iatapay.rs
@@ -281,7 +281,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 9724a00edfe..220b8f4a416 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -317,7 +317,6 @@ impl
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs
index a9a82c4d45e..5759a4f8a0a 100644
--- a/crates/router/src/connector/mollie.rs
+++ b/crates/router/src/connector/mollie.rs
@@ -239,7 +239,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs
index 21bbb3745af..160a135b173 100644
--- a/crates/router/src/connector/multisafepay.rs
+++ b/crates/router/src/connector/multisafepay.rs
@@ -267,7 +267,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs
index 2ff4e0648bc..f0a490cfbd1 100644
--- a/crates/router/src/connector/nexinets.rs
+++ b/crates/router/src/connector/nexinets.rs
@@ -210,7 +210,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs
index 85b7b1da054..d2834d99664 100644
--- a/crates/router/src/connector/nmi.rs
+++ b/crates/router/src/connector/nmi.rs
@@ -222,7 +222,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs
index ce8aa36fb00..625f080d295 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/router/src/connector/noon.rs
@@ -204,7 +204,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs
index 8286d148f18..b2bcb39c5ea 100644
--- a/crates/router/src/connector/nuvei.rs
+++ b/crates/router/src/connector/nuvei.rs
@@ -567,7 +567,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/opayo.rs b/crates/router/src/connector/opayo.rs
index 47a0c331705..c64cfe7ea0c 100644
--- a/crates/router/src/connector/opayo.rs
+++ b/crates/router/src/connector/opayo.rs
@@ -183,7 +183,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs
index af6b6d7e034..2a997e0adb0 100644
--- a/crates/router/src/connector/opennode.rs
+++ b/crates/router/src/connector/opennode.rs
@@ -179,7 +179,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs
index c02b1dc2844..6baa01f087e 100644
--- a/crates/router/src/connector/payeezy.rs
+++ b/crates/router/src/connector/payeezy.rs
@@ -390,7 +390,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs
index 88ac385fcc6..81123b21369 100644
--- a/crates/router/src/connector/payme.rs
+++ b/crates/router/src/connector/payme.rs
@@ -478,7 +478,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index e0c7ecaabfb..a16b458ef35 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -357,7 +357,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs
index 5f2d4409058..dd78c214ee6 100644
--- a/crates/router/src/connector/payu.rs
+++ b/crates/router/src/connector/payu.rs
@@ -525,7 +525,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs
index 4cd8f610594..32303dc073d 100644
--- a/crates/router/src/connector/powertranz.rs
+++ b/crates/router/src/connector/powertranz.rs
@@ -204,7 +204,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index 69b66126a8d..d0a5259157d 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -197,7 +197,6 @@ impl
>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
let timestamp = date_time::now_unix_timestamp();
let salt = Alphanumeric.sample_string(&mut rand::thread_rng(), 12);
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs
index 8694f4b78be..ae777b28600 100644
--- a/crates/router/src/connector/shift4.rs
+++ b/crates/router/src/connector/shift4.rs
@@ -235,7 +235,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs
index 2e54677a1d2..6ef1b6a29c7 100644
--- a/crates/router/src/connector/square.rs
+++ b/crates/router/src/connector/square.rs
@@ -424,7 +424,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs
index da035f0d913..52287639071 100644
--- a/crates/router/src/connector/stax.rs
+++ b/crates/router/src/connector/stax.rs
@@ -358,7 +358,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index e24ccc58815..5e31a89bed5 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -787,7 +787,6 @@ impl
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs
index cb708336a6d..fdfb50b0384 100644
--- a/crates/router/src/connector/trustpay.rs
+++ b/crates/router/src/connector/trustpay.rs
@@ -548,7 +548,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/tsys.rs b/crates/router/src/connector/tsys.rs
index 32bce79b503..b7e4f5aece2 100644
--- a/crates/router/src/connector/tsys.rs
+++ b/crates/router/src/connector/tsys.rs
@@ -154,7 +154,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs
index 72479d14c6f..ed9acec34c9 100644
--- a/crates/router/src/connector/worldline.rs
+++ b/crates/router/src/connector/worldline.rs
@@ -500,7 +500,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
>,
connectors: &Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(types::PaymentsAuthorizeType::get_http_method(self))
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 857be775665..20185cf81ab 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -438,7 +438,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs
index 1bcdc5218d9..6bee7111b55 100644
--- a/crates/router/src/connector/zen.rs
+++ b/crates/router/src/connector/zen.rs
@@ -222,7 +222,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- self.validate_capture_method(req.request.capture_method)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 272ccfced60..7313195a2d0 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -69,6 +69,10 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
+ connector
+ .connector
+ .validate_capture_method(self.request.capture_method)
+ .to_payment_failed_response()?;
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
|
refactor
|
remove redundant validate_capture_method call (#2171)
|
93dcd98640a31e41f0d66d2ece2396e536adefae
|
2023-05-19 11:36:36
|
ThisIsMani
|
feat(redis_interface): implement `MGET` command (#1206)
| false
|
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index c283ee575aa..1547158e6eb 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -290,6 +290,46 @@ 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
+ .into_report()
+ .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,
|
feat
|
implement `MGET` command (#1206)
|
00686cc17fa20635e5fc04130aefb08a7c6c8cfc
|
2024-11-25 19:05:33
|
Pa1NarK
|
ci(cypress): use ubuntu runner (#6655)
| false
|
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index 84680c945e1..e07b4e48d6f 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -24,7 +24,7 @@ env:
jobs:
runner:
name: Run Cypress tests
- runs-on: hyperswitch-runners
+ runs-on: ubuntu-latest
services:
redis:
@@ -190,7 +190,7 @@ jobs:
ROUTER__SERVER__WORKERS: 4
shell: bash -leuo pipefail {0}
run: |
- scripts/execute_cypress.sh --parallel 3
+ scripts/execute_cypress.sh
kill "${{ env.PID }}"
|
ci
|
use ubuntu runner (#6655)
|
fb836618a66f57fca5c78aa1c2a255792ab1dfb4
|
2024-06-13 16:41:43
|
Shankar Singh C
|
feat(router): include the pre-routing connectors in Apple Pay retries (#4952)
| false
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 0641c842390..04983ed8b19 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2085,7 +2085,15 @@ pub async fn list_payment_methods(
}
if let Some(choice) = result.get(&intermediate.payment_method_type) {
- intermediate.connector == choice.connector.connector_name.to_string()
+ if let Some(first_routable_connector) = choice.first() {
+ intermediate.connector
+ == first_routable_connector
+ .connector
+ .connector_name
+ .to_string()
+ } else {
+ false
+ }
} else {
false
}
@@ -2105,26 +2113,32 @@ pub async fn list_payment_methods(
let mut pre_routing_results: HashMap<
api_enums::PaymentMethodType,
- routing_types::RoutableConnectorChoice,
+ storage::PreRoutingConnectorChoice,
> = HashMap::new();
- for (pm_type, choice) in result {
- let routable_choice = routing_types::RoutableConnectorChoice {
- #[cfg(feature = "backwards_compatibility")]
- choice_kind: routing_types::RoutableChoiceKind::FullStruct,
- connector: choice
- .connector
- .connector_name
- .to_string()
- .parse::<api_enums::RoutableConnectors>()
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- #[cfg(feature = "connector_choice_mca_id")]
- merchant_connector_id: choice.connector.merchant_connector_id,
- #[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: choice.sub_label,
- };
-
- pre_routing_results.insert(pm_type, routable_choice);
+ for (pm_type, routing_choice) in result {
+ let mut routable_choice_list = vec![];
+ for choice in routing_choice {
+ let routable_choice = routing_types::RoutableConnectorChoice {
+ #[cfg(feature = "backwards_compatibility")]
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: choice
+ .connector
+ .connector_name
+ .to_string()
+ .parse::<api_enums::RoutableConnectors>()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ #[cfg(feature = "connector_choice_mca_id")]
+ merchant_connector_id: choice.connector.merchant_connector_id.clone(),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: choice.sub_label,
+ };
+ routable_choice_list.push(routable_choice);
+ }
+ pre_routing_results.insert(
+ pm_type,
+ storage::PreRoutingConnectorChoice::Multiple(routable_choice_list),
+ );
}
let redis_conn = db
@@ -2135,15 +2149,28 @@ pub async fn list_payment_methods(
let mut val = Vec::new();
for (payment_method_type, routable_connector_choice) in &pre_routing_results {
+ let routable_connector_list = match routable_connector_choice {
+ storage::PreRoutingConnectorChoice::Single(routable_connector) => {
+ vec![routable_connector.clone()]
+ }
+ storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
+ routable_connector_list.clone()
+ }
+ };
+
+ let first_routable_connector = routable_connector_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+
#[cfg(not(feature = "connector_choice_mca_id"))]
let connector_label = get_connector_label(
payment_intent.business_country,
payment_intent.business_label.as_ref(),
#[cfg(not(feature = "connector_choice_mca_id"))]
- routable_connector_choice.sub_label.as_ref(),
+ first_routable_connector.sub_label.as_ref(),
#[cfg(feature = "connector_choice_mca_id")]
None,
- routable_connector_choice.connector.to_string().as_str(),
+ first_routable_connector.connector.to_string().as_str(),
);
#[cfg(not(feature = "connector_choice_mca_id"))]
let matched_mca = filtered_mcas
@@ -2152,7 +2179,7 @@ pub async fn list_payment_methods(
#[cfg(feature = "connector_choice_mca_id")]
let matched_mca = filtered_mcas.iter().find(|m| {
- routable_connector_choice.merchant_connector_id.as_ref()
+ first_routable_connector.merchant_connector_id.as_ref()
== Some(&m.merchant_connector_id)
});
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e1290637dbe..50eedcfb568 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3182,32 +3182,51 @@ where
.as_ref()
.zip(payment_data.payment_attempt.payment_method_type.as_ref())
{
- if let (Some(choice), None) = (
+ if let (Some(routable_connector_choice), None) = (
pre_routing_results.get(storage_pm_type),
&payment_data.token_data,
) {
- let connector_data = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &choice.connector.to_string(),
- api::GetToken::Connector,
- #[cfg(feature = "connector_choice_mca_id")]
- choice.merchant_connector_id.clone(),
- #[cfg(not(feature = "connector_choice_mca_id"))]
- None,
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received")?;
+ let routable_connector_list = match routable_connector_choice {
+ storage::PreRoutingConnectorChoice::Single(routable_connector) => {
+ vec![routable_connector.clone()]
+ }
+ storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
+ routable_connector_list.clone()
+ }
+ };
+
+ let mut pre_routing_connector_data_list = vec![];
+
+ let first_routable_connector = routable_connector_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
- routing_data.routed_through = Some(choice.connector.to_string());
+ routing_data.routed_through = Some(first_routable_connector.connector.to_string());
#[cfg(feature = "connector_choice_mca_id")]
{
routing_data
.merchant_connector_id
- .clone_from(&choice.merchant_connector_id);
+ .clone_from(&first_routable_connector.merchant_connector_id);
}
#[cfg(not(feature = "connector_choice_mca_id"))]
{
- routing_data.business_sub_label = choice.sub_label.clone();
+ routing_data.business_sub_label = first_routable_connector.sub_label.clone();
+ }
+
+ for connector_choice in routable_connector_list.clone() {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &connector_choice.connector.to_string(),
+ api::GetToken::Connector,
+ #[cfg(feature = "connector_choice_mca_id")]
+ connector_choice.merchant_connector_id.clone(),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ None,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Invalid connector name received")?;
+
+ pre_routing_connector_data_list.push(connector_data);
}
#[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))]
@@ -3224,8 +3243,11 @@ where
merchant_account,
payment_data,
key_store,
- connector_data.clone(),
- choice.merchant_connector_id.clone().as_ref(),
+ &pre_routing_connector_data_list,
+ first_routable_connector
+ .merchant_connector_id
+ .clone()
+ .as_ref(),
)
.await?;
@@ -3237,7 +3259,13 @@ where
}
}
- return Ok(ConnectorCallType::PreDetermined(connector_data));
+ let first_pre_routing_connector_data_list = pre_routing_connector_data_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+
+ return Ok(ConnectorCallType::PreDetermined(
+ first_pre_routing_connector_data_list.clone(),
+ ));
}
}
@@ -3614,11 +3642,22 @@ where
}));
let mut final_list: Vec<api::SessionConnectorData> = Vec::new();
- for (routed_pm_type, choice) in pre_routing_results.into_iter() {
- if let Some(session_connector_data) =
- payment_methods.remove(&(choice.to_string(), routed_pm_type))
- {
- final_list.push(session_connector_data);
+ for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() {
+ let routable_connector_list = match pre_routing_choice {
+ storage::PreRoutingConnectorChoice::Single(routable_connector) => {
+ vec![routable_connector.clone()]
+ }
+ storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
+ routable_connector_list.clone()
+ }
+ };
+ for routable_connector in routable_connector_list {
+ if let Some(session_connector_data) =
+ payment_methods.remove(&(routable_connector.to_string(), routed_pm_type))
+ {
+ final_list.push(session_connector_data);
+ break;
+ }
}
}
@@ -3666,8 +3705,11 @@ where
if !routing_enabled_pms.contains(&connector_data.payment_method_type) {
final_list.push(connector_data);
} else if let Some(choice) = result.get(&connector_data.payment_method_type) {
- if connector_data.connector.connector_name == choice.connector.connector_name {
- connector_data.business_sub_label = choice.sub_label.clone();
+ let routing_choice = choice
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+ if connector_data.connector.connector_name == routing_choice.connector.connector_name {
+ connector_data.business_sub_label = routing_choice.sub_label.clone();
final_list.push(connector_data);
}
}
@@ -3678,7 +3720,10 @@ where
if !routing_enabled_pms.contains(&connector_data.payment_method_type) {
final_list.push(connector_data);
} else if let Some(choice) = result.get(&connector_data.payment_method_type) {
- if connector_data.connector.connector_name == choice.connector.connector_name {
+ let routing_choice = choice
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+ if connector_data.connector.connector_name == routing_choice.connector.connector_name {
final_list.push(connector_data);
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 052c4b19286..7eada733aed 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4033,7 +4033,7 @@ pub async fn get_apple_pay_retryable_connectors<F>(
merchant_account: &domain::MerchantAccount,
payment_data: &mut PaymentData<F>,
key_store: &domain::MerchantKeyStore,
- decided_connector_data: api::ConnectorData,
+ pre_routing_connector_data_list: &[api::ConnectorData],
merchant_connector_id: Option<&String>,
) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
where
@@ -4048,13 +4048,17 @@ where
field_name: "profile_id",
})?;
+ let pre_decided_connector_data_first = pre_routing_connector_data_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+
let merchant_connector_account_type = get_merchant_connector_account(
&state,
merchant_account.merchant_id.as_str(),
payment_data.creds_identifier.to_owned(),
key_store,
profile_id,
- &decided_connector_data.connector_name.to_string(),
+ &pre_decided_connector_data_first.connector_name.to_string(),
merchant_connector_id,
)
.await?;
@@ -4081,7 +4085,7 @@ where
Some(profile_id.to_string()),
);
- let mut connector_data_list = vec![decided_connector_data.clone()];
+ let mut connector_data_list = vec![pre_decided_connector_data_first.clone()];
for merchant_connector_account in profile_specific_merchant_connector_account_list {
if is_apple_pay_simplified_flow(
@@ -4118,16 +4122,31 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
+ let mut routing_connector_data_list = Vec::new();
+
+ pre_routing_connector_data_list.iter().for_each(|pre_val| {
+ routing_connector_data_list.push(pre_val.merchant_connector_id.clone())
+ });
+
+ fallback_connetors_list.iter().for_each(|fallback_val| {
+ routing_connector_data_list
+ .iter()
+ .all(|val| *val != fallback_val.merchant_connector_id)
+ .then(|| {
+ routing_connector_data_list.push(fallback_val.merchant_connector_id.clone())
+ });
+ });
+
// connector_data_list is the list of connectors for which Apple Pay simplified flow is configured.
- // This list is arranged in the same order as the merchant's default fallback connectors configuration.
- let mut ordered_connector_data_list = vec![decided_connector_data.clone()];
- fallback_connetors_list
+ // This list is arranged in the same order as the merchant's connectors routingconfiguration.
+
+ let mut ordered_connector_data_list = Vec::new();
+
+ routing_connector_data_list
.iter()
- .for_each(|fallback_connector| {
+ .for_each(|merchant_connector_id| {
let connector_data = connector_data_list.iter().find(|connector_data| {
- fallback_connector.merchant_connector_id == connector_data.merchant_connector_id
- && fallback_connector.merchant_connector_id
- != decided_connector_data.merchant_connector_id
+ *merchant_connector_id == connector_data.merchant_connector_id
});
if let Some(connector_data_details) = connector_data {
ordered_connector_data_list.push(connector_data_details.clone());
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 4394637d99a..3afb933d467 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -855,7 +855,8 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
pub async fn perform_session_flow_routing(
session_input: SessionFlowRoutingInput<'_>,
transaction_type: &api_enums::TransactionType,
-) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice>> {
+) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>>
+{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
@@ -962,8 +963,10 @@ pub async fn perform_session_flow_routing(
);
}
- let mut result: FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice> =
- FxHashMap::default();
+ let mut result: FxHashMap<
+ api_enums::PaymentMethodType,
+ Vec<routing_types::SessionRoutingChoice>,
+ > = FxHashMap::default();
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
@@ -985,20 +988,37 @@ pub async fn perform_session_flow_routing(
))]
profile_id: session_input.payment_intent.profile_id.clone(),
};
- let maybe_choice =
- perform_session_routing_for_pm_type(session_pm_input, transaction_type).await?;
-
- // (connector, sub_label)
- if let Some(data) = maybe_choice {
- result.insert(
- pm_type,
- routing_types::SessionRoutingChoice {
- connector: data.0,
+ let routable_connector_choice_option =
+ perform_session_routing_for_pm_type(&session_pm_input, transaction_type).await?;
+
+ if let Some(routable_connector_choice) = routable_connector_choice_option {
+ let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
+
+ for selection in routable_connector_choice {
+ let connector_name = selection.connector.to_string();
+ if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ &session_pm_input.state.clone().conf.connectors,
+ &connector_name,
+ get_token.clone(),
+ #[cfg(feature = "connector_choice_mca_id")]
+ selection.merchant_connector_id,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ None,
+ )
+ .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
#[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: data.1,
- payment_method_type: pm_type,
- },
- );
+ let sub_label = selection.sub_label;
+
+ session_routing_choice.push(routing_types::SessionRoutingChoice {
+ connector: connector_data,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: sub_label,
+ payment_method_type: pm_type,
+ });
+ }
+ }
+ result.insert(pm_type, session_routing_choice);
}
}
@@ -1006,9 +1026,9 @@ pub async fn perform_session_flow_routing(
}
async fn perform_session_routing_for_pm_type(
- session_pm_input: SessionRoutingPmTypeInput<'_>,
+ session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
-) -> RoutingResult<Option<(api::ConnectorData, Option<String>)>> {
+) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let chosen_connectors = match session_pm_input.routing_algorithm {
@@ -1091,7 +1111,7 @@ async fn perform_session_routing_for_pm_type(
&session_pm_input.state.clone(),
session_pm_input.key_store,
fallback,
- session_pm_input.backend_input,
+ session_pm_input.backend_input.clone(),
None,
#[cfg(feature = "business_profile_routing")]
session_pm_input.profile_id.clone(),
@@ -1100,32 +1120,11 @@ async fn perform_session_routing_for_pm_type(
.await?;
}
- let mut final_choice: Option<(api::ConnectorData, Option<String>)> = None;
-
- for selection in final_selection {
- let connector_name = selection.connector.to_string();
- if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
- let connector_data = api::ConnectorData::get_connector_by_name(
- &session_pm_input.state.clone().conf.connectors,
- &connector_name,
- get_token.clone(),
- #[cfg(feature = "connector_choice_mca_id")]
- selection.merchant_connector_id,
- #[cfg(not(feature = "connector_choice_mca_id"))]
- None,
- )
- .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
- #[cfg(not(feature = "connector_choice_mca_id"))]
- let sub_label = selection.sub_label;
- #[cfg(feature = "connector_choice_mca_id")]
- let sub_label = None;
-
- final_choice = Some((connector_data, sub_label));
- break;
- }
+ if final_selection.is_empty() {
+ Ok(None)
+ } else {
+ Ok(Some(final_selection))
}
-
- Ok(final_choice)
}
pub fn make_dsl_input_for_surcharge(
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 77550bedabe..79c8b2ed2f0 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -81,14 +81,21 @@ pub struct RoutingData {
pub struct PaymentRoutingInfo {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
- Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>,
+ Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentRoutingInfoInner {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
- Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>,
+ Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(untagged)]
+pub enum PreRoutingConnectorChoice {
+ Single(routing::RoutableConnectorChoice),
+ Multiple(Vec<routing::RoutableConnectorChoice>),
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
feat
|
include the pre-routing connectors in Apple Pay retries (#4952)
|
e4956820fdfea8f637600b7fd03ac666f3b19c21
|
2023-02-11 14:10:58
|
Sampras Lopes
|
fix(router): feature gate openssl deps for basilisk feature (#536)
| false
|
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 277df67584b..ad3df36b5ca 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -12,7 +12,7 @@ build = "src/build.rs"
[features]
default = ["kv_store", "stripe", "oltp", "olap","accounts_cache"]
kms = ["aws-config", "aws-sdk-kms"]
-basilisk = []
+basilisk = ["josekit"]
stripe = ["dep:serde_qs"]
sandbox = ["kms", "stripe", "basilisk"]
olap = []
@@ -48,7 +48,7 @@ frunk_core = "0.4.1"
futures = "0.3.25"
hex = "0.4.3"
http = "0.2.8"
-josekit = "0.8.1"
+josekit = { version = "0.8.1", optional = true }
jsonwebtoken = "8.2.0"
literally = "0.1.3"
maud = { version = "0.24", features = ["actix-web"] }
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 2cb010ec151..9646df7d593 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -8,16 +8,16 @@ use router_env::{instrument, tracing};
#[cfg(not(feature = "basilisk"))]
use crate::types::storage;
use crate::{
- core::{
- errors::{self, CustomResult, RouterResult},
- payment_methods::transformers as payment_methods,
- },
- logger, routes, services,
+ core::errors::{self, CustomResult, RouterResult},
+ logger, routes,
types::api,
- utils::{self, BytesExt, StringExt},
+ utils::{self, StringExt},
};
-
+#[cfg(feature = "basilisk")]
+use crate::{core::payment_methods::transformers as payment_methods, services, utils::BytesExt};
+#[cfg(feature = "basilisk")]
const VAULT_SERVICE_NAME: &str = "CARD";
+#[cfg(feature = "basilisk")]
const VAULT_VERSION: &str = "0";
pub struct SupplementaryVaultData {
@@ -381,6 +381,7 @@ impl Vault {
}
//------------------------------------------------TokenizeService------------------------------------------------
+#[cfg(feature = "basilisk")]
pub async fn create_tokenize(
state: &routes::AppState,
value1: String,
@@ -444,6 +445,7 @@ pub async fn create_tokenize(
}
}
+#[cfg(feature = "basilisk")]
pub async fn get_tokenized_data(
state: &routes::AppState,
lookup_key: &str,
@@ -500,6 +502,7 @@ pub async fn get_tokenized_data(
}
}
+#[cfg(feature = "basilisk")]
pub async fn delete_tokenized_data(
state: &routes::AppState,
lookup_key: &str,
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 9d40d39cda7..3492b3e5c50 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -1,11 +1,14 @@
pub mod api;
pub mod authentication;
+#[cfg(feature = "basilisk")]
pub mod encryption;
pub mod logger;
use std::sync::Arc;
-pub use self::{api::*, encryption::*};
+pub use self::api::*;
+#[cfg(feature = "basilisk")]
+pub use self::encryption::*;
use crate::connection::{diesel_make_pg_pool, PgPool};
#[derive(Clone)]
diff --git a/crates/router/src/services/encryption.rs b/crates/router/src/services/encryption.rs
index 0fe1d59eae4..be2bc5aa93c 100644
--- a/crates/router/src/services/encryption.rs
+++ b/crates/router/src/services/encryption.rs
@@ -1,6 +1,7 @@
use std::{num::Wrapping, str};
use error_stack::{report, IntoReport, ResultExt};
+#[cfg(feature = "basilisk")]
use josekit::jwe;
use rand;
use ring::{aead::*, error::Unspecified};
@@ -175,6 +176,7 @@ pub fn get_key_id(keys: &Jwekey) -> &str {
}
}
+#[cfg(feature = "basilisk")]
pub async fn encrypt_jwe(
keys: &Jwekey,
msg: &str,
|
fix
|
feature gate openssl deps for basilisk feature (#536)
|
f47c06a517749384f85bae90dd9bfe5f2d813444
|
2022-12-01 16:53:30
|
Sangamesh Kulkarni
|
feat: handle no connector txn id (#39)
| false
|
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index bade2c64b43..a098fb68d6d 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -67,6 +67,9 @@ pub(crate) enum ErrorCode {
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")]
MerchantAccountNotFound,
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")]
+ ResourceIdNotFound,
+
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant connector account")]
MerchantConnectorAccountNotFound,
@@ -327,6 +330,7 @@ impl From<ApiErrorResponse> for ErrorCode {
ApiErrorResponse::PaymentNotFound => ErrorCode::PaymentNotFound,
ApiErrorResponse::PaymentMethodNotFound => ErrorCode::PaymentMethodNotFound,
ApiErrorResponse::MerchantAccountNotFound => ErrorCode::MerchantAccountNotFound,
+ ApiErrorResponse::ResourceIdNotFound => ErrorCode::ResourceIdNotFound,
ApiErrorResponse::MerchantConnectorAccountNotFound => {
ErrorCode::MerchantConnectorAccountNotFound
}
@@ -402,6 +406,7 @@ impl actix_web::ResponseError for ErrorCode {
| ErrorCode::DuplicateMandate
| ErrorCode::SuccessfulPaymentNotFound
| ErrorCode::AddressNotFound
+ | ErrorCode::ResourceIdNotFound
| ErrorCode::PaymentIntentUnexpectedState { .. } => StatusCode::BAD_REQUEST,
ErrorCode::RefundFailed | ErrorCode::InternalServerError => {
StatusCode::INTERNAL_SERVER_ERROR
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 2344e9a6892..5b45bd58c7c 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -214,7 +214,7 @@ impl<F, T>
&item.response.result.code,
)?),
response: Ok(types::PaymentsResponseData {
- connector_transaction_id: item.response.id,
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
//TODO: Add redirection details here
redirection_data: None,
redirect: false,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index f620a50316f..eaf8e8af548 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -381,7 +381,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>>
Ok(types::RouterData {
status,
response: Ok(types::PaymentsResponseData {
- connector_transaction_id: item.response.psp_reference,
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference),
redirection_data: None,
redirect: false,
}),
@@ -421,7 +421,7 @@ pub fn get_adyen_response(
};
let payments_response_data = types::PaymentsResponseData {
- connector_transaction_id: response.psp_reference,
+ resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference),
redirection_data: None,
redirect: false,
};
@@ -476,7 +476,7 @@ pub fn get_redirection_response(
// We don't get connector transaction id for redirections in Adyen.
let payments_response_data = types::PaymentsResponseData {
- connector_transaction_id: "".to_string(),
+ resource_id: types::ResponseId::NoResponseId,
redirection_data: Some(redirection_data),
redirect: true,
};
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 34372342fa7..982a031f452 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -1,3 +1,4 @@
+use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use crate::{
@@ -299,7 +300,9 @@ impl<F, T>
Some(err) => Err(err),
None => {
Ok(types::PaymentsResponseData {
- connector_transaction_id: item.response.transaction_response.transaction_id,
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.transaction_response.transaction_id,
+ ),
//TODO: Add redirection details here
redirection_data: None,
redirect: false,
@@ -468,8 +471,15 @@ impl TryFrom<&types::PaymentsSyncRouterData> for AuthorizedotnetCreateSyncReques
let transaction_id = item
.response
.as_ref()
- .map(|payment_response_data| payment_response_data.connector_transaction_id.clone())
- .ok();
+ .ok()
+ .map(|payment_response_data| {
+ payment_response_data
+ .resource_id
+ .get_connector_transaction_id()
+ })
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
+
let merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?;
let payload = AuthorizedotnetCreateSyncRequest {
@@ -571,7 +581,9 @@ impl<F, Req>
enums::AttemptStatus::from(item.response.transaction.transaction_status);
Ok(types::RouterData {
response: Ok(types::PaymentsResponseData {
- connector_transaction_id: item.response.transaction.transaction_id,
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.transaction.transaction_id,
+ ),
redirection_data: None,
redirect: false,
}),
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index c7971d426ad..d52e17c740f 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -190,7 +190,7 @@ impl<F, Req>
Ok(types::RouterData {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData {
- connector_transaction_id: item.response.id,
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
redirect: redirection_data.is_some(),
redirection_data,
}),
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 5bacb47de18..fa34c2dfb4f 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -314,7 +314,7 @@ impl<F, T>
// statement_descriptor_suffix: item.response.statement_descriptor_suffix.map(|x| x.as_str()),
// three_ds_form,
response: Ok(types::PaymentsResponseData {
- connector_transaction_id: item.response.id,
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
redirect: redirection_data.is_some(),
redirection_data,
}),
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index 5a836916a6f..2a54dabc127 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -93,6 +93,8 @@ pub enum ApiErrorResponse {
MerchantAccountNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Merchant connector account does not exist in our records.")]
MerchantConnectorAccountNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Resource ID does not exist in our records.")]
+ ResourceIdNotFound,
#[error(error_type = ErrorType::DuplicateRequest, code = "RE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")]
DuplicateMandate,
#[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Mandate does not exist in our records.")]
@@ -161,6 +163,7 @@ impl actix_web::ResponseError for ApiErrorResponse {
| ApiErrorResponse::MandateNotFound
| ApiErrorResponse::ClientSecretInvalid
| ApiErrorResponse::SuccessfulPaymentNotFound
+ | ApiErrorResponse::ResourceIdNotFound
| ApiErrorResponse::AddressNotFound => StatusCode::BAD_REQUEST, // 400
ApiErrorResponse::DuplicateMerchantAccount
| ApiErrorResponse::DuplicateMerchantConnectorAccount
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6d281dd27b1..a982ee55747 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -123,7 +123,12 @@ async fn payment_response_ut<F: Clone, T>(
storage::PaymentAttemptUpdate::ResponseUpdate {
status: router_data.status,
- connector_transaction_id: Some(response.connector_transaction_id),
+ connector_transaction_id: Some(
+ response
+ .resource_id
+ .get_connector_transaction_id()
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?,
+ ),
authentication_type: None,
payment_method_id: Some(router_data.payment_method_id),
redirect: Some(response.redirect),
@@ -147,7 +152,12 @@ async fn payment_response_ut<F: Clone, T>(
.attach_printable("Could not parse the connector response")?;
let connector_response_update = storage::ConnectorResponseUpdate::ResponseUpdate {
- connector_transaction_id: Some(connector_response.connector_transaction_id.clone()),
+ connector_transaction_id: Some(
+ connector_response
+ .resource_id
+ .get_connector_transaction_id()
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?,
+ ),
authentication_data,
encoded_data: payment_data.connector_response.encoded_data.clone(),
};
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index d51028c86ad..d54ce4f1181 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -68,7 +68,7 @@ where
.connector_transaction_id
.as_ref()
.map(|id| types::PaymentsResponseData {
- connector_transaction_id: id.to_string(),
+ resource_id: types::ResponseId::ConnectorTransactionId(id.to_string()),
//TODO: Add redirection details here
redirection_data: None,
redirect: false,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 6ea5615485c..6dc3d1fb4cb 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -12,10 +12,12 @@ pub mod storage;
use std::marker::PhantomData;
+use error_stack::{IntoReport, ResultExt};
+
pub use self::connector::Connector;
use self::{api::payments, storage::enums};
pub use crate::core::payments::PaymentAddress;
-use crate::{core::errors::ApiErrorResponse, services};
+use crate::{core::errors, services};
pub type PaymentsAuthorizeRouterData =
RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
@@ -108,12 +110,35 @@ pub struct PaymentsCancelData {
}
#[derive(Debug, Clone)]
pub struct PaymentsResponseData {
- pub connector_transaction_id: String,
+ pub resource_id: ResponseId,
// pub amount_received: Option<i32>, // Calculation for amount received not in place yet
pub redirection_data: Option<services::RedirectForm>,
pub redirect: bool,
}
+#[derive(Debug, Clone, Default)]
+pub enum ResponseId {
+ ConnectorTransactionId(String),
+ EncodedData(String),
+ #[default]
+ NoResponseId,
+}
+
+impl ResponseId {
+ pub fn get_connector_transaction_id(
+ &self,
+ ) -> errors::CustomResult<String, errors::ValidationError> {
+ match self {
+ Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
+ _ => Err(errors::ValidationError::IncorrectValueProvided {
+ field_name: "connector_transaction_id",
+ })
+ .into_report()
+ .attach_printable("Expected connector transaction ID not found"),
+ }
+ }
+}
+
#[derive(Debug, Clone)]
pub struct RefundsData {
pub refund_id: String,
@@ -205,15 +230,15 @@ pub struct ErrorResponse {
impl ErrorResponse {
pub fn get_not_implemented() -> Self {
Self {
- code: ApiErrorResponse::NotImplemented.error_code(),
- message: ApiErrorResponse::NotImplemented.error_message(),
+ code: errors::ApiErrorResponse::NotImplemented.error_code(),
+ message: errors::ApiErrorResponse::NotImplemented.error_message(),
reason: None,
}
}
}
-impl From<ApiErrorResponse> for ErrorResponse {
- fn from(error: ApiErrorResponse) -> Self {
+impl From<errors::ApiErrorResponse> for ErrorResponse {
+ fn from(error: errors::ApiErrorResponse) -> Self {
Self {
code: error.error_code(),
message: error.error_message(),
@@ -224,6 +249,6 @@ impl From<ApiErrorResponse> for ErrorResponse {
impl Default for ErrorResponse {
fn default() -> Self {
- Self::from(ApiErrorResponse::InternalServerError)
+ Self::from(errors::ApiErrorResponse::InternalServerError)
}
}
diff --git a/crates/router/src/types/storage/enums.rs b/crates/router/src/types/storage/enums.rs
index 5f5c24b28f6..5056dea750c 100644
--- a/crates/router/src/types/storage/enums.rs
+++ b/crates/router/src/types/storage/enums.rs
@@ -478,7 +478,6 @@ pub enum PaymentMethodType {
Copy,
Debug,
Eq,
- Hash,
PartialEq,
router_derive::DieselEnum,
serde::Deserialize,
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index e27b9e91ce3..b67ecb17668 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -207,8 +207,12 @@ async fn refund_for_successful_payments() {
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let mut refund_request = construct_refund_router_data();
- refund_request.request.connector_transaction_id =
- response.response.unwrap().connector_transaction_id;
+ refund_request.request.connector_transaction_id = response
+ .response
+ .unwrap()
+ .resource_id
+ .get_connector_transaction_id()
+ .unwrap();
let response = services::api::execute_connector_processing_step(
&state,
connector_integration,
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index d6de0f8a857..1d932d94450 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -171,8 +171,13 @@ async fn test_checkout_refund_success() {
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let mut refund_request = construct_refund_router_data();
- refund_request.request.connector_transaction_id =
- response.response.unwrap().connector_transaction_id;
+
+ refund_request.request.connector_transaction_id = response
+ .response
+ .unwrap()
+ .resource_id
+ .get_connector_transaction_id()
+ .unwrap();
let response = services::api::execute_connector_processing_step(
&state,
@@ -267,8 +272,12 @@ async fn test_checkout_refund_failure() {
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let mut refund_request = construct_refund_router_data();
- refund_request.request.connector_transaction_id =
- response.response.unwrap().connector_transaction_id;
+ refund_request.request.connector_transaction_id = response
+ .response
+ .unwrap()
+ .resource_id
+ .get_connector_transaction_id()
+ .unwrap();
// Higher amout than that of payment
refund_request.request.refund_amount = 696969;
|
feat
|
handle no connector txn id (#39)
|
b2f7dd13925a1429e316cd9eaf0e2d31d46b6d4a
|
2023-11-23 19:46:14
|
Chethan Rao
|
docs: add Rust locker information in architecture doc (#2964)
| false
|
diff --git a/docs/architecture.md b/docs/architecture.md
index 3ab3b6a7eaf..24b0c726205 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -49,12 +49,7 @@ In addition to the database, Hyperswitch incorporates Redis for two main purpose
## Locker
-The application utilizes a Locker, which consists of two distinct services: Temporary Locker and Permanent Locker. These services are responsible for securely storing payment-method information and adhere strictly to **Payment Card Industry Data Security Standard (PCI DSS)** compliance standards, ensuring that all payment-related data is handled and stored securely.
-
-- **Temporary Locker:** The Temporary Locker service handles the temporary storage of payment-method information. This temporary storage facilitates the smooth processing of transactions and reduces the exposure of sensitive information.
-- **Permanent Locker:** The Permanent Locker service is responsible for the long-term storage of payment-method related data. It securely stores card details, such as cardholder information or payment method details, for future reference or recurring payments.
-
-> Currently, Locker service is not part of open-source
+The application utilizes a Rust locker built with a GDPR compliant PII (personal identifiable information) storage. It also uses secure encryption algorithms to be fully compliant with **PCI DSS** (Payment Card Industry Data Security Standard) requirements, this ensures that all payment-related data is handled and stored securely. You can find the source code of locker [here](https://github.com/juspay/hyperswitch-card-vault).
## Monitoring
diff --git a/docs/imgs/hyperswitch-architecture.png b/docs/imgs/hyperswitch-architecture.png
index 18f42f9a55c..f73f60f3e35 100644
Binary files a/docs/imgs/hyperswitch-architecture.png and b/docs/imgs/hyperswitch-architecture.png differ
|
docs
|
add Rust locker information in architecture doc (#2964)
|
351087fc7f1a3417da19b55f0228dd2eac54b0fc
|
2023-01-25 21:13:21
|
Narayan Bhat
|
feat(stripe): add support for afterpay clearpay through stripe (#441)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index ddbf7325fd6..fc761d2851d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -321,14 +321,20 @@ pub struct CCard {
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
-pub enum KlarnaRedirectIssuer {
- Stripe,
+pub enum KlarnaIssuer {
+ Klarna,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
-pub enum KlarnaSdkIssuer {
- Klarna,
+pub enum AffirmIssuer {
+ Affirm,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum AfterpayClearpayIssuer {
+ AfterpayClearpay,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
@@ -337,7 +343,7 @@ pub enum PayLaterData {
/// For KlarnaRedirect as PayLater Option
KlarnaRedirect {
/// The issuer name of the redirect
- issuer_name: KlarnaRedirectIssuer,
+ issuer_name: KlarnaIssuer,
/// The billing email
billing_email: String,
// The billing country code
@@ -345,15 +351,26 @@ pub enum PayLaterData {
},
/// For Klarna Sdk as PayLater Option
KlarnaSdk {
- /// The issuer name of the redirect
- issuer_name: KlarnaSdkIssuer,
+ /// The issuer name of the sdk
+ issuer_name: KlarnaIssuer,
/// The token for the sdk workflow
token: String,
},
- /// For Affirm redirect flow
+ /// For Affirm redirect as PayLater Option
AffirmRedirect {
- /// The billing email address
+ /// The issuer name of affirm redirect issuer
+ issuer_name: AffirmIssuer,
+ /// The billing email
+ billing_email: String,
+ },
+ /// For AfterpayClearpay redirect as PayLater Option
+ AfterpayClearpayRedirect {
+ /// The issuer name of afterpayclearpay redirect issuer
+ issuer_name: AfterpayClearpayIssuer,
+ /// The billing email
billing_email: String,
+ /// The billing name
+ billing_name: String,
},
}
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index b98fd22d8c4..d6841c257cf 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -344,7 +344,8 @@ impl
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<String>, errors::ConnectorError> {
- let stripe_req = utils::Encode::<stripe::PaymentIntentRequest>::convert_and_url_encode(req)
+ let req = stripe::PaymentIntentRequest::try_from(req)?;
+ let stripe_req = utils::Encode::<stripe::PaymentIntentRequest>::encode(&req)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(stripe_req))
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 2d7ef4a24c6..2f18b3fd29a 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1,6 +1,9 @@
use std::str::FromStr;
+use api_models::{self, payments};
+use common_utils::fp_utils;
use error_stack::{IntoReport, ResultExt};
+use masking::ExposeInterface;
use serde::{Deserialize, Serialize};
use strum::EnumString;
use url::Url;
@@ -81,7 +84,7 @@ pub struct PaymentIntentRequest {
pub mandate: Option<String>,
pub description: Option<String>,
#[serde(flatten)]
- pub shipping: Address,
+ pub shipping: StripeShippingAddress,
#[serde(flatten)]
pub payment_data: Option<StripePaymentMethodData>,
pub capture_method: StripeCaptureMethod,
@@ -129,6 +132,8 @@ pub struct StripePayLaterData {
pub billing_email: String,
#[serde(rename = "payment_method_data[billing_details][address][country]")]
pub billing_country: Option<String>,
+ #[serde(rename = "payment_method_data[billing_details][name]")]
+ pub billing_name: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
@@ -137,6 +142,7 @@ pub enum StripePaymentMethodData {
Card(StripeCardData),
Klarna(StripePayLaterData),
Affirm(StripePayLaterData),
+ AfterpayClearpay(StripePayLaterData),
Bank,
Wallet,
Paypal,
@@ -148,10 +154,46 @@ pub enum StripePaymentMethodType {
Card,
Klarna,
Affirm,
+ AfterpayClearpay,
+}
+
+fn validate_shipping_address_against_payment_method(
+ shipping_address: &StripeShippingAddress,
+ payment_method: &payments::PaymentMethod,
+) -> Result<(), errors::ConnectorError> {
+ if let payments::PaymentMethod::PayLater(payments::PayLaterData::AfterpayClearpayRedirect {
+ ..
+ }) = payment_method
+ {
+ fp_utils::when(shipping_address.name.is_none(), || {
+ Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "shipping.first_name".to_string(),
+ })
+ })?;
+
+ fp_utils::when(shipping_address.line1.is_none(), || {
+ Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "shipping.line1".to_string(),
+ })
+ })?;
+
+ fp_utils::when(shipping_address.country.is_none(), || {
+ Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "shipping.country".to_string(),
+ })
+ })?;
+
+ fp_utils::when(shipping_address.zip.is_none(), || {
+ Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "shipping.zip".to_string(),
+ })
+ })?;
+ }
+ Ok(())
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = errors::ConnectorError;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let metadata_order_id = item.payment_id.to_string();
let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1");
@@ -166,71 +208,32 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
.clone()
.and_then(|mandate_ids| mandate_ids.connector_mandate_id)
{
- None => (
- Some(match item.request.payment_method_data {
- api::PaymentMethod::Card(ref ccard) => StripePaymentMethodData::Card({
- let payment_method_auth_type = match item.auth_type {
- enums::AuthenticationType::ThreeDs => Auth3ds::Any,
- enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic,
- };
- StripeCardData {
- payment_method_types: StripePaymentMethodType::Card,
- payment_method_data_type: StripePaymentMethodType::Card,
- payment_method_data_card_number: ccard.card_number.clone(),
- payment_method_data_card_exp_month: ccard.card_exp_month.clone(),
- payment_method_data_card_exp_year: ccard.card_exp_year.clone(),
- payment_method_data_card_cvc: ccard.card_cvc.clone(),
- payment_method_auth_type,
- }
- }),
- api::PaymentMethod::BankTransfer => StripePaymentMethodData::Bank,
- api::PaymentMethod::PayLater(ref pay_later_data) => match pay_later_data {
- api_models::payments::PayLaterData::KlarnaRedirect {
- billing_email,
- billing_country,
- ..
- } => StripePaymentMethodData::Klarna(StripePayLaterData {
- payment_method_types: StripePaymentMethodType::Klarna,
- payment_method_data_type: StripePaymentMethodType::Klarna,
- billing_email: billing_email.to_string(),
- billing_country: Some(billing_country.to_string()),
- }),
- api_models::payments::PayLaterData::AffirmRedirect {
- billing_email,
- } => StripePaymentMethodData::Affirm(StripePayLaterData {
- payment_method_types: StripePaymentMethodType::Affirm,
- payment_method_data_type: StripePaymentMethodType::Affirm,
- billing_email: billing_email.to_string(),
- billing_country: None,
- }),
- _ => Err(error_stack::report!(
- errors::ConnectorError::NotImplemented(String::from("Stripe does not support payment through provided payment method"))
- ))?,
- },
- api::PaymentMethod::Wallet(_) => StripePaymentMethodData::Wallet,
- api::PaymentMethod::Paypal => StripePaymentMethodData::Paypal,
- }),
- None,
- ),
+ None => {
+ let payment_method: StripePaymentMethodData =
+ (item.request.payment_method_data.clone(), item.auth_type).try_into()?;
+ (Some(payment_method), None)
+ }
Some(mandate_id) => (None, Some(mandate_id)),
}
};
let shipping_address = match item.address.shipping.clone() {
- Some(mut shipping) => Address {
+ Some(mut shipping) => StripeShippingAddress {
city: shipping.address.as_mut().and_then(|a| a.city.take()),
country: shipping.address.as_mut().and_then(|a| a.country.take()),
line1: shipping.address.as_mut().and_then(|a| a.line1.take()),
line2: shipping.address.as_mut().and_then(|a| a.line2.take()),
- postal_code: shipping.address.as_mut().and_then(|a| a.zip.take()),
+ zip: shipping.address.as_mut().and_then(|a| a.zip.take()),
state: shipping.address.as_mut().and_then(|a| a.state.take()),
- name: shipping.address.as_mut().map(|a| {
- format!(
- "{} {}",
- a.first_name.clone().expose_option().unwrap_or_default(),
- a.last_name.clone().expose_option().unwrap_or_default()
- )
- .into()
+ name: shipping.address.as_mut().and_then(|a| {
+ a.first_name.as_ref().map(|first_name| {
+ format!(
+ "{} {}",
+ first_name.clone().expose(),
+ a.last_name.clone().expose_option().unwrap_or_default()
+ )
+ .into()
+ })
}),
phone: shipping.phone.map(|p| {
format!(
@@ -241,9 +244,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
.into()
}),
},
- None => Address::default(),
+ None => StripeShippingAddress::default(),
};
+ validate_shipping_address_against_payment_method(
+ &shipping_address,
+ &item.request.payment_method_data,
+ )?;
+
let off_session = item
.request
.off_session
@@ -402,6 +410,7 @@ impl<F, T>
} => mandate_options.map(|mandate_options| mandate_options.reference),
StripePaymentMethodOptions::Klarna {} => None,
StripePaymentMethodOptions::Affirm {} => None,
+ StripePaymentMethodOptions::AfterpayClearpay {} => None,
});
Ok(Self {
@@ -457,6 +466,7 @@ impl<F, T>
} => mandate_options.map(|mandate_option| mandate_option.reference),
StripePaymentMethodOptions::Klarna {} => None,
StripePaymentMethodOptions::Affirm {} => None,
+ StripePaymentMethodOptions::AfterpayClearpay {} => None,
});
Ok(Self {
@@ -620,7 +630,7 @@ pub struct ErrorResponse {
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
-pub struct Address {
+pub struct StripeShippingAddress {
#[serde(rename = "shipping[address][city]")]
pub city: Option<String>,
#[serde(rename = "shipping[address][country]")]
@@ -630,7 +640,7 @@ pub struct Address {
#[serde(rename = "shipping[address][line2]")]
pub line2: Option<Secret<String>>,
#[serde(rename = "shipping[address][postal_code]")]
- pub postal_code: Option<Secret<String>>,
+ pub zip: Option<Secret<String>>,
#[serde(rename = "shipping[address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "shipping[name]")]
@@ -690,6 +700,7 @@ pub enum StripePaymentMethodOptions {
},
Klarna {},
Affirm {},
+ AfterpayClearpay {},
}
// #[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
// pub struct Card
@@ -782,7 +793,7 @@ pub struct StripeWebhookObjectId {
}
impl TryFrom<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentMethodData {
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = errors::ConnectorError;
fn try_from(
(pm_data, auth_type): (api::PaymentMethod, enums::AuthenticationType),
) -> Result<Self, Self::Error> {
@@ -813,12 +824,31 @@ impl TryFrom<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentM
payment_method_data_type: StripePaymentMethodType::Klarna,
billing_email,
billing_country: Some(billing_country),
+ billing_name: None,
+ })),
+ api_models::payments::PayLaterData::AffirmRedirect { billing_email, .. } => {
+ Ok(Self::Affirm(StripePayLaterData {
+ payment_method_types: StripePaymentMethodType::Affirm,
+ payment_method_data_type: StripePaymentMethodType::Affirm,
+ billing_email,
+ billing_country: None,
+ billing_name: None,
+ }))
+ }
+ api_models::payments::PayLaterData::AfterpayClearpayRedirect {
+ billing_email,
+ billing_name,
+ ..
+ } => Ok(Self::AfterpayClearpay(StripePayLaterData {
+ payment_method_types: StripePaymentMethodType::AfterpayClearpay,
+ payment_method_data_type: StripePaymentMethodType::AfterpayClearpay,
+ billing_email,
+ billing_country: None,
+ billing_name: Some(billing_name),
})),
- _ => Err(error_stack::report!(
- errors::ConnectorError::NotImplemented(String::from(
- "Stripe does not support payment through provided payment method"
- ))
- )),
+ _ => Err(errors::ConnectorError::NotImplemented(String::from(
+ "Stripe does not support payment through provided payment method",
+ ))),
},
api::PaymentMethod::Wallet(_) => Ok(Self::Wallet),
api::PaymentMethod::Paypal => Ok(Self::Paypal),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index b2c7dffd3c3..450572adaa8 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -2,7 +2,7 @@ use std::marker::PhantomData;
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode};
-use error_stack::ResultExt;
+use error_stack::{self, ResultExt};
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use uuid::Uuid;
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index 3c8a7d857b3..cd3329c526b 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -25,7 +25,7 @@ Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------------------------|
-| Sandbox | <https://sandbox.hyperswitch.io> |
+| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://router.juspay.io> |
## Authentication
@@ -80,8 +80,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::NextActionType,
api_models::payments::Metadata,
api_models::payments::WalletData,
- api_models::payments::KlarnaRedirectIssuer,
- api_models::payments::KlarnaSdkIssuer,
+ api_models::payments::KlarnaIssuer,
+ api_models::payments::AffirmIssuer,
+ api_models::payments::AfterpayClearpayIssuer,
api_models::payments::NextAction,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
diff --git a/openapi/generated.json b/openapi/generated.json
index 4dce27f50d3..5c30411af97 100644
--- a/openapi/generated.json
+++ b/openapi/generated.json
@@ -203,6 +203,14 @@
}
}
},
+ "AffirmIssuer": {
+ "type": "string",
+ "enum": ["affirm"]
+ },
+ "AfterpayClearpayIssuer": {
+ "type": "string",
+ "enum": ["afterpay_clearpay"]
+ },
"AuthenticationType": {
"type": "string",
"enum": ["three_ds", "no_three_ds"]
@@ -778,11 +786,7 @@
"requires_capture"
]
},
- "KlarnaRedirectIssuer": {
- "type": "string",
- "enum": ["stripe"]
- },
- "KlarnaSdkIssuer": {
+ "KlarnaIssuer": {
"type": "string",
"enum": ["klarna"]
},
@@ -1071,7 +1075,7 @@
"required": ["issuer_name", "billing_email", "billing_country"],
"properties": {
"issuer_name": {
- "$ref": "#/components/schemas/KlarnaRedirectIssuer"
+ "$ref": "#/components/schemas/KlarnaIssuer"
},
"billing_email": {
"type": "string",
@@ -1094,7 +1098,7 @@
"required": ["issuer_name", "token"],
"properties": {
"issuer_name": {
- "$ref": "#/components/schemas/KlarnaSdkIssuer"
+ "$ref": "#/components/schemas/KlarnaIssuer"
},
"token": {
"type": "string",
@@ -1110,12 +1114,39 @@
"properties": {
"affirm_redirect": {
"type": "object",
- "description": "For Affirm redirect flow",
- "required": ["billing_email"],
+ "description": "For Affirm redirect as PayLater Option",
+ "required": ["issuer_name", "billing_email"],
"properties": {
+ "issuer_name": {
+ "$ref": "#/components/schemas/AffirmIssuer"
+ },
"billing_email": {
"type": "string",
- "description": "The billing email address"
+ "description": "The billing email"
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": ["afterpay_clearpay_redirect"],
+ "properties": {
+ "afterpay_clearpay_redirect": {
+ "type": "object",
+ "description": "For AfterpayClearpay redirect as PayLater Option",
+ "required": ["issuer_name", "billing_email", "billing_name"],
+ "properties": {
+ "issuer_name": {
+ "$ref": "#/components/schemas/AfterpayClearpayIssuer"
+ },
+ "billing_email": {
+ "type": "string",
+ "description": "The billing email"
+ },
+ "billing_name": {
+ "type": "string",
+ "description": "The billing name"
}
}
}
@@ -2036,6 +2067,9 @@
"error_message": {
"type": "string"
},
+ "error_code": {
+ "type": "string"
+ },
"created_at": {
"type": "string",
"format": "date-time"
|
feat
|
add support for afterpay clearpay through stripe (#441)
|
775dcc5a4e3b41dd1e4d0e4c47eccca15a8a4b3a
|
2025-02-06 19:13:13
|
Kashif
|
chore(roles): remove redundant variant from PermissionGroup (#6985)
| false
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 0234fbea6d5..1faa3b90aa8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2936,8 +2936,6 @@ pub enum PermissionGroup {
ReconReportsManage,
ReconOpsView,
ReconOpsManage,
- // TODO: To be deprecated, make sure DB is migrated before removing
- ReconOps,
}
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)]
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index e02838b3e00..b4413dfa3b3 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -40,10 +40,10 @@ fn get_group_description(group: PermissionGroup) -> &'static str {
PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details",
PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
- PermissionGroup::ReconReportsView => "View and access reconciliation reports and analytics",
+ PermissionGroup::ReconReportsView => "View reconciliation reports and analytics",
PermissionGroup::ReconReportsManage => "Manage reconciliation reports",
- PermissionGroup::ReconOpsView => "View and access reconciliation operations",
- PermissionGroup::ReconOpsManage | PermissionGroup::ReconOps => "Manage reconciliation operations",
+ PermissionGroup::ReconOpsView => "View and access all reconciliation operations including reports and analytics",
+ PermissionGroup::ReconOpsManage => "Manage all reconciliation operations including reports and analytics",
}
}
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
index ceb943950d5..0cdb68ec8d7 100644
--- a/crates/router/src/services/authorization/permission_groups.rs
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -33,7 +33,6 @@ impl PermissionGroupExt for PermissionGroup {
| Self::OrganizationManage
| Self::AccountManage
| Self::ReconOpsManage
- | Self::ReconOps
| Self::ReconReportsManage => PermissionScope::Write,
}
}
@@ -50,7 +49,7 @@ impl PermissionGroupExt for PermissionGroup {
| Self::MerchantDetailsManage
| Self::AccountView
| Self::AccountManage => ParentGroup::Account,
- Self::ReconOpsView | Self::ReconOpsManage | Self::ReconOps => ParentGroup::ReconOps,
+ Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps,
Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports,
}
}
@@ -86,7 +85,7 @@ impl PermissionGroupExt for PermissionGroup {
}
Self::ReconOpsView => vec![Self::ReconOpsView],
- Self::ReconOpsManage | Self::ReconOps => vec![Self::ReconOpsView, Self::ReconOpsManage],
+ Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage],
Self::ReconReportsView => vec![Self::ReconReportsView],
Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage],
diff --git a/migrations/2025-01-03-104019_migrate_permission_group_for_recon/down.sql b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/down.sql
new file mode 100644
index 00000000000..e0ac49d1ecf
--- /dev/null
+++ b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/down.sql
@@ -0,0 +1 @@
+SELECT 1;
diff --git a/migrations/2025-01-03-104019_migrate_permission_group_for_recon/up.sql b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/up.sql
new file mode 100644
index 00000000000..0fa04632dce
--- /dev/null
+++ b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/up.sql
@@ -0,0 +1,3 @@
+UPDATE roles
+SET groups = array_replace(groups, 'recon_ops', 'recon_ops_manage')
+WHERE 'recon_ops' = ANY(groups);
|
chore
|
remove redundant variant from PermissionGroup (#6985)
|
91354232e03a8dbd9ad9eccc8620eac321765dd7
|
2024-05-09 11:31:46
|
Mani Chandra
|
feat(users): Create API to Verify TOTP (#4597)
| false
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 1d91a47bf56..e9eb5157095 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -17,7 +17,7 @@ use crate::user::{
ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse,
SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse,
TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate,
- VerifyEmailRequest,
+ VerifyEmailRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -74,7 +74,8 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsResponse,
TokenResponse,
UserFromEmailRequest,
- BeginTotpResponse
+ BeginTotpResponse,
+ VerifyTotpRequest
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 0dde73d0545..7dbf867d1a0 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -252,3 +252,8 @@ pub struct TotpSecret {
pub totp_url: Secret<String>,
pub recovery_codes: Vec<Secret<String>>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VerifyTotpRequest {
+ pub totp: Option<Secret<String>>,
+}
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index ddcd10c32e4..580e34ba7e8 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -66,6 +66,10 @@ pub enum UserErrors {
RoleNameParsingError,
#[error("RoleNameAlreadyExists")]
RoleNameAlreadyExists,
+ #[error("TOTPNotSetup")]
+ TotpNotSetup,
+ #[error("InvalidTOTP")]
+ InvalidTotp,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -169,6 +173,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::RoleNameAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None))
}
+ Self::TotpNotSetup => {
+ AER::BadRequest(ApiError::new(sub_code, 36, self.get_error_message(), None))
+ }
+ Self::InvalidTotp => {
+ AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None))
+ }
}
}
}
@@ -205,6 +215,8 @@ impl UserErrors {
Self::InvalidRoleOperationWithMessage(error_message) => error_message,
Self::RoleNameParsingError => "Invalid Role Name",
Self::RoleNameAlreadyExists => "Role name already exists",
+ Self::TotpNotSetup => "TOTP not setup",
+ Self::InvalidTotp => "Invalid TOTP",
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e01ed4b1a23..83cdd1d318b 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1642,3 +1642,65 @@ pub async fn begin_totp(
}),
}))
}
+
+pub async fn verify_totp(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_api::VerifyTotpRequest,
+) -> UserResponse<user_api::TokenResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if let Some(user_totp) = req.totp {
+ if user_from_db.get_totp_status() == TotpStatus::NotSet {
+ return Err(UserErrors::TotpNotSetup.into());
+ }
+
+ let user_totp_secret = user_from_db
+ .decrypt_and_get_totp_secret(&state)
+ .await?
+ .ok_or(UserErrors::InternalServerError)?;
+
+ let totp =
+ utils::user::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?;
+
+ if totp
+ .generate_current()
+ .change_context(UserErrors::InternalServerError)?
+ != user_totp.expose()
+ {
+ return Err(UserErrors::InvalidTotp.into());
+ }
+
+ if user_from_db.get_totp_status() == TotpStatus::InProgress {
+ state
+ .store
+ .update_user_by_user_id(
+ user_from_db.get_user_id(),
+ storage_user::UserUpdate::TotpUpdate {
+ totp_status: Some(TotpStatus::Set),
+ totp_secret: None,
+ totp_recovery_codes: None,
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ }
+ }
+
+ let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?;
+ let next_flow = current_flow.next(user_from_db, &state).await?;
+ let token = next_flow.get_token(&state).await?;
+
+ auth::cookies::set_cookie_response(
+ user_api::TokenResponse {
+ token: token.clone(),
+ token_type: next_flow.get_flow().into(),
+ },
+ token,
+ )
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 1560578f66f..49a8e063183 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1199,7 +1199,8 @@ impl User {
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
)
- .service(web::resource("/totp/begin").route(web::get().to(totp_begin)));
+ .service(web::resource("/totp/begin").route(web::get().to(totp_begin)))
+ .service(web::resource("/totp/verify").route(web::post().to(totp_verify)));
#[cfg(feature = "email")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5bef68073f0..ee42cc50fe3 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -211,7 +211,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
- | Flow::TotpBegin => Self::User,
+ | Flow::TotpBegin
+ | Flow::TotpVerify => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index db12729d01a..a901988e51e 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -626,3 +626,21 @@ pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpRes
))
.await
}
+
+pub async fn totp_verify(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_api::VerifyTotpRequest>,
+) -> HttpResponse {
+ let flow = Flow::TotpVerify;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, user, req_body, _| user_core::verify_totp(state, user, req_body),
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 00881626c1c..45f5d74d6f6 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -4,7 +4,7 @@ use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
use common_enums::TokenPurpose;
-use common_utils::{errors::CustomResult, pii};
+use common_utils::{crypto::Encryptable, errors::CustomResult, pii};
use diesel_models::{
enums::{TotpStatus, UserStatus},
organization as diesel_org,
@@ -909,6 +909,32 @@ impl UserFromStorage {
pub fn get_totp_status(&self) -> TotpStatus {
self.0.totp_status
}
+
+ pub async fn decrypt_and_get_totp_secret(
+ &self,
+ state: &AppState,
+ ) -> UserResult<Option<Secret<String>>> {
+ if self.0.totp_secret.is_none() {
+ return Ok(None);
+ }
+
+ let user_key_store = state
+ .store
+ .get_user_key_store_by_user_id(
+ self.get_user_id(),
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(domain_types::decrypt::<String, masking::WithType>(
+ self.0.totp_secret.clone(),
+ user_key_store.key.peek(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .map(Encryptable::into_inner))
+ }
}
impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b3252302413..9ea86167fcf 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -398,6 +398,8 @@ pub enum Flow {
UserFromEmail,
/// Begin TOTP
TotpBegin,
+ /// Verify TOTP
+ TotpVerify,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
feat
|
Create API to Verify TOTP (#4597)
|
dd484a0a4fd06fd93a3634daf5ed461a65385d82
|
2024-08-26 05:53:19
|
github-actions
|
chore(version): 2024.08.26.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d6bd13388c..b7772125b0b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,16 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.08.26.0
+
+### Features
+
+- **connector:** [Adyen] add dispute flows for adyen connector ([#5514](https://github.com/juspay/hyperswitch/pull/5514)) ([`ad9f91b`](https://github.com/juspay/hyperswitch/commit/ad9f91b37cc39c8fb594b48ac60c5e945a0f561f))
+
+**Full Changelog:** [`2024.08.23.0...2024.08.26.0`](https://github.com/juspay/hyperswitch/compare/2024.08.23.0...2024.08.26.0)
+
+- - -
+
## 2024.08.23.0
### Features
|
chore
|
2024.08.26.0
|
b45e4ca2a3788823701bdeac2e2a8c1147bb071a
|
2024-01-25 12:28:59
|
Jeeva Ramachandran
|
fix(euclid_wasm): include `payouts` feature in `default` features (#3392)
| false
|
diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml
index d9f5330a1b8..13296bcde62 100644
--- a/crates/euclid_wasm/Cargo.toml
+++ b/crates/euclid_wasm/Cargo.toml
@@ -10,7 +10,7 @@ rust-version.workspace = true
crate-type = ["cdylib"]
[features]
-default = ["connector_choice_bcompat", "connector_choice_mca_id"]
+default = ["connector_choice_bcompat","payouts", "connector_choice_mca_id"]
release = ["connector_choice_bcompat", "connector_choice_mca_id"]
connector_choice_bcompat = ["api_models/connector_choice_bcompat"]
connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"]
@@ -18,6 +18,7 @@ dummy_connector = ["kgraph_utils/dummy_connector", "connector_configs/dummy_conn
production = ["connector_configs/production"]
development = ["connector_configs/development"]
sandbox = ["connector_configs/sandbox"]
+payouts = []
[dependencies]
api_models = { version = "0.1.0", path = "../api_models", package = "api_models" }
|
fix
|
include `payouts` feature in `default` features (#3392)
|
09c2a5c2a90f2773b00ab11ad67ab149f8225e3a
|
2024-02-13 05:49:28
|
github-actions
|
chore(version): 2024.02.13.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a235e98653f..02392fda11f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,35 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.02.13.0
+
+### Features
+
+- **pm_list:** Add required fields for giropay ([#3194](https://github.com/juspay/hyperswitch/pull/3194)) ([`33df352`](https://github.com/juspay/hyperswitch/commit/33df3520d1daa3e399b567b85f6a75d1b10bca13))
+- **router:** Add `delete_evidence` api for disputes ([#3608](https://github.com/juspay/hyperswitch/pull/3608)) ([`1dc660f`](https://github.com/juspay/hyperswitch/commit/1dc660f80453306e86a3ea77d09829118100b59b))
+- **stripe:** Send billing address to stripe for card payment ([#3611](https://github.com/juspay/hyperswitch/pull/3611)) ([`67df984`](https://github.com/juspay/hyperswitch/commit/67df984c27841ee303eae6ba55577d8bf1ef68fa))
+
+### Bug Fixes
+
+- **payment_link:** Changed media screen queries size for web to mobile view ([#3574](https://github.com/juspay/hyperswitch/pull/3574)) ([`cc6759b`](https://github.com/juspay/hyperswitch/commit/cc6759bd2d4207ad874a69546cb0a48db70b8629))
+- **payment_methods:**
+ - Unmask last4 digits of card when listing payment methods for customer ([#3617](https://github.com/juspay/hyperswitch/pull/3617)) ([`834142e`](https://github.com/juspay/hyperswitch/commit/834142e690871e5cc8e48c2fed08621e325d5d8f))
+ - Unmask last4 when metadata changed during /payments ([#3633](https://github.com/juspay/hyperswitch/pull/3633)) ([`8b1206d`](https://github.com/juspay/hyperswitch/commit/8b1206d31c6c3490c96212158252f2858e5d3f7c))
+
+### Refactors
+
+- Introducing `hyperswitch_interface` crates ([#3536](https://github.com/juspay/hyperswitch/pull/3536)) ([`b6754a7`](https://github.com/juspay/hyperswitch/commit/b6754a7de87a417ca3f95822e970cb92b741cb95))
+
+### Miscellaneous Tasks
+
+- **configs:** [Volt] Add configs for wasm for production ([#3406](https://github.com/juspay/hyperswitch/pull/3406)) ([`a9749c9`](https://github.com/juspay/hyperswitch/commit/a9749c93a579aa063a96e367e92232354f977fa6))
+- Address Rust 1.76 clippy lints ([#3605](https://github.com/juspay/hyperswitch/pull/3605)) ([`c55eb0a`](https://github.com/juspay/hyperswitch/commit/c55eb0afca9d43866378e8e0891ba8118a3dca39))
+- Chore(deps): bump the cargo group across 1 directories with 1 update ([#3624](https://github.com/juspay/hyperswitch/pull/3624)) ([`97e9e30`](https://github.com/juspay/hyperswitch/commit/97e9e30dbed74864ecb140dccd3c61c4b28931f8))
+
+**Full Changelog:** [`2024.02.12.0...2024.02.13.0`](https://github.com/juspay/hyperswitch/compare/2024.02.12.0...2024.02.13.0)
+
+- - -
+
## 2024.02.12.0
### Features
|
chore
|
2024.02.13.0
|
c8c0cb765e8a511aae0b3a4f94115bb07d122c9d
|
2024-07-04 15:06:06
|
Sahkal Poddar
|
feat(core): Added integrity framework for Authorize and Sync flow with connector as Stripe (#5109)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 60186807283..d0b9894970b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2356,16 +2356,15 @@ dependencies = [
[[package]]
name = "curve25519-dalek"
-version = "4.1.2"
+version = "4.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0a677b8922c94e01bdbb12126b0bc852f00447528dee1782229af9c720c3f348"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
dependencies = [
"cfg-if 1.0.0",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
- "platforms",
"rustc_version 0.4.0",
"subtle",
"zeroize",
@@ -5269,12 +5268,6 @@ version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
-[[package]]
-name = "platforms"
-version = "3.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db23d408679286588f4d4644f965003d056e3dd5abcaaa938116871d7ce2fee7"
-
[[package]]
name = "plotters"
version = "0.3.5"
diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rs
index 538a75e1b2b..48e9ce56703 100644
--- a/crates/api_models/src/errors/types.rs
+++ b/crates/api_models/src/errors/types.rs
@@ -77,6 +77,8 @@ pub struct Extra {
pub connector: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub connector_transaction_id: Option<String>,
}
#[derive(Serialize, Debug, Clone)]
diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs
index e4c59ba2a31..d5e86985041 100644
--- a/crates/common_utils/src/errors.rs
+++ b/crates/common_utils/src/errors.rs
@@ -69,6 +69,15 @@ pub enum ValidationError {
InvalidValue { message: String },
}
+/// Integrity check errors.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct IntegrityCheckError {
+ /// Field names for which integrity check failed!
+ pub field_names: String,
+ /// Connector transaction reference id
+ pub connector_transaction_id: Option<String>,
+}
+
/// Cryptographic algorithm errors
#[derive(Debug, thiserror::Error)]
pub enum CryptoError {
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
index faca8cd7bbf..782376519c2 100644
--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -271,6 +271,12 @@ pub enum ApiErrorResponse {
InvalidCookie,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
+ #[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}", ignore = "status_code")]
+ IntegrityCheckFailed {
+ reason: String,
+ field_names: String,
+ connector_transaction_id: Option<String>,
+ },
#[error(error_type = ErrorType::ProcessingError, code = "HE_06", message = "Missing tenant id")]
MissingTenantId,
#[error(error_type = ErrorType::ProcessingError, code = "HE_06", message = "Invalid tenant id: {tenant_id}")]
@@ -609,6 +615,19 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::ExtendedCardInfoNotFound => {
AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
}
+ Self::IntegrityCheckFailed {
+ reason,
+ field_names,
+ connector_transaction_id
+ } => AER::InternalServerError(ApiError::new(
+ "IE",
+ 0,
+ format!("{} as data mismatched for {}", reason, field_names),
+ Some(Extra {
+ connector_transaction_id: connector_transaction_id.to_owned(),
+ ..Default::default()
+ })
+ )),
Self::MissingTenantId => {
AER::InternalServerError(ApiError::new("HE", 6, "Missing Tenant ID in the request".to_string(), None))
}
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index 79f0c78b7b9..edf465e0d28 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -1,6 +1,6 @@
use std::{collections::HashMap, marker::PhantomData};
-use common_utils::{id_type, types::MinorUnit};
+use common_utils::{errors::IntegrityCheckError, id_type, types::MinorUnit};
use masking::Secret;
use crate::{payment_address::PaymentAddress, payment_method_data};
@@ -70,6 +70,8 @@ pub struct RouterData<Flow, Request, Response> {
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
+
+ pub integrity_check: Result<(), IntegrityCheckError>,
}
// Different patterns of authentication.
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 8fc32991a32..8496827ff25 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -62,6 +62,23 @@ pub struct PaymentsAuthorizeData {
// New amount for amount frame work
pub minor_amount: MinorUnit,
+ pub integrity_object: Option<AuthoriseIntegrityObject>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct AuthoriseIntegrityObject {
+ /// Authorise amount
+ pub amount: MinorUnit,
+ /// Authorise currency
+ pub currency: storage_enums::Currency,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct SyncIntegrityObject {
+ /// Sync amount
+ pub amount: Option<MinorUnit>,
+ /// Sync currency
+ pub currency: Option<storage_enums::Currency>,
}
#[derive(Debug, serde::Deserialize, Clone)]
@@ -348,6 +365,9 @@ pub struct PaymentsSyncData {
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub currency: storage_enums::Currency,
pub payment_experience: Option<common_enums::PaymentExperience>,
+
+ pub amount: MinorUnit,
+ pub integrity_object: Option<SyncIntegrityObject>,
}
#[derive(Debug, Default, Clone)]
diff --git a/crates/hyperswitch_interfaces/src/integrity.rs b/crates/hyperswitch_interfaces/src/integrity.rs
new file mode 100644
index 00000000000..e9b9828bb4a
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/integrity.rs
@@ -0,0 +1,168 @@
+use common_utils::errors::IntegrityCheckError;
+use hyperswitch_domain_models::router_request_types::{
+ AuthoriseIntegrityObject, PaymentsAuthorizeData, PaymentsSyncData, SyncIntegrityObject,
+};
+
+/// Connector Integrity trait to check connector data integrity
+pub trait FlowIntegrity {
+ /// Output type for the connector
+ type IntegrityObject;
+ /// helps in connector integrity check
+ fn compare(
+ req_integrity_object: Self::IntegrityObject,
+ res_integrity_object: Self::IntegrityObject,
+ connector_transaction_id: Option<String>,
+ ) -> Result<(), IntegrityCheckError>;
+}
+
+/// Trait to get connector integrity object based on request and response
+pub trait GetIntegrityObject<T: FlowIntegrity> {
+ /// function to get response integrity object
+ fn get_response_integrity_object(&self) -> Option<T::IntegrityObject>;
+ /// function to get request integrity object
+ fn get_request_integrity_object(&self) -> T::IntegrityObject;
+}
+
+/// Trait to check flow type, based on which various integrity checks will be performed
+pub trait CheckIntegrity<Request, T> {
+ /// Function to check to initiate integrity check
+ fn check_integrity(
+ &self,
+ request: &Request,
+ connector_transaction_id: Option<String>,
+ ) -> Result<(), IntegrityCheckError>;
+}
+
+impl<T, Request> CheckIntegrity<Request, T> for PaymentsAuthorizeData
+where
+ T: FlowIntegrity,
+ Request: GetIntegrityObject<T>,
+{
+ fn check_integrity(
+ &self,
+ request: &Request,
+ connector_transaction_id: Option<String>,
+ ) -> Result<(), IntegrityCheckError> {
+ match request.get_response_integrity_object() {
+ Some(res_integrity_object) => {
+ let req_integrity_object = request.get_request_integrity_object();
+ T::compare(
+ req_integrity_object,
+ res_integrity_object,
+ connector_transaction_id,
+ )
+ }
+ None => Ok(()),
+ }
+ }
+}
+
+impl<T, Request> CheckIntegrity<Request, T> for PaymentsSyncData
+where
+ T: FlowIntegrity,
+ Request: GetIntegrityObject<T>,
+{
+ fn check_integrity(
+ &self,
+ request: &Request,
+ connector_transaction_id: Option<String>,
+ ) -> Result<(), IntegrityCheckError> {
+ match request.get_response_integrity_object() {
+ Some(res_integrity_object) => {
+ let req_integrity_object = request.get_request_integrity_object();
+ T::compare(
+ req_integrity_object,
+ res_integrity_object,
+ connector_transaction_id,
+ )
+ }
+ None => Ok(()),
+ }
+ }
+}
+
+impl FlowIntegrity for AuthoriseIntegrityObject {
+ type IntegrityObject = Self;
+ fn compare(
+ req_integrity_object: Self,
+ res_integrity_object: Self,
+ connector_transaction_id: Option<String>,
+ ) -> Result<(), IntegrityCheckError> {
+ let mut mismatched_fields = Vec::new();
+
+ if req_integrity_object.amount != res_integrity_object.amount {
+ mismatched_fields.push("amount".to_string());
+ }
+
+ if req_integrity_object.currency != res_integrity_object.currency {
+ mismatched_fields.push("currency".to_string());
+ }
+
+ if mismatched_fields.is_empty() {
+ Ok(())
+ } else {
+ let field_names = mismatched_fields.join(", ");
+
+ Err(IntegrityCheckError {
+ field_names,
+ connector_transaction_id,
+ })
+ }
+ }
+}
+
+impl FlowIntegrity for SyncIntegrityObject {
+ type IntegrityObject = Self;
+ fn compare(
+ req_integrity_object: Self,
+ res_integrity_object: Self,
+ connector_transaction_id: Option<String>,
+ ) -> Result<(), IntegrityCheckError> {
+ let mut mismatched_fields = Vec::new();
+
+ if req_integrity_object.amount != res_integrity_object.amount {
+ mismatched_fields.push("amount".to_string());
+ }
+
+ if req_integrity_object.currency != res_integrity_object.currency {
+ mismatched_fields.push("currency".to_string());
+ }
+
+ if mismatched_fields.is_empty() {
+ Ok(())
+ } else {
+ let field_names = mismatched_fields.join(", ");
+
+ Err(IntegrityCheckError {
+ field_names,
+ connector_transaction_id,
+ })
+ }
+ }
+}
+
+impl GetIntegrityObject<AuthoriseIntegrityObject> for PaymentsAuthorizeData {
+ fn get_response_integrity_object(&self) -> Option<AuthoriseIntegrityObject> {
+ self.integrity_object.clone()
+ }
+
+ fn get_request_integrity_object(&self) -> AuthoriseIntegrityObject {
+ AuthoriseIntegrityObject {
+ amount: self.minor_amount,
+ currency: self.currency,
+ }
+ }
+}
+
+impl GetIntegrityObject<SyncIntegrityObject> for PaymentsSyncData {
+ fn get_response_integrity_object(&self) -> Option<SyncIntegrityObject> {
+ self.integrity_object.clone()
+ }
+
+ fn get_request_integrity_object(&self) -> SyncIntegrityObject {
+ SyncIntegrityObject {
+ amount: Some(self.amount),
+ currency: Some(self.currency),
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs
index 66403f641b5..7eb35d46a42 100644
--- a/crates/hyperswitch_interfaces/src/lib.rs
+++ b/crates/hyperswitch_interfaces/src/lib.rs
@@ -9,6 +9,8 @@ pub mod consts;
pub mod encryption_interface;
pub mod errors;
pub mod events;
+/// connector integrity check interface
+pub mod integrity;
pub mod metrics;
pub mod secrets_interface;
pub mod types;
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 0e538bb3389..f72b71570a0 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -264,6 +264,12 @@ pub enum StripeErrorCode {
PaymentMethodDeleteFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
+ #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")]
+ IntegrityCheckFailed {
+ reason: String,
+ field_names: String,
+ connector_transaction_id: Option<String>,
+ },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")]
InvalidTenant,
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")]
@@ -650,6 +656,15 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
Self::InvalidWalletToken { wallet_name }
}
errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound,
+ errors::ApiErrorResponse::IntegrityCheckFailed {
+ reason,
+ field_names,
+ connector_transaction_id,
+ } => Self::IntegrityCheckFailed {
+ reason,
+ field_names,
+ connector_transaction_id,
+ },
errors::ApiErrorResponse::InvalidTenant { tenant_id: _ }
| errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant,
errors::ApiErrorResponse::AmountConversionFailed { amount_type } => {
@@ -741,6 +756,7 @@ impl actix_web::ResponseError for StripeErrorCode {
Self::ExternalConnectorError { status_code, .. } => {
StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
+ Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR,
Self::PaymentBlockedError { code, .. } => {
StatusCode::from_u16(*code).unwrap_or(StatusCode::OK)
}
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index a3e0844842c..40f85843755 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -298,7 +298,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);
let capture_amount_in_minor_units = match response.data.price_amount {
- Some(ref amount) => Some(utils::convert_back(
+ Some(ref amount) => Some(utils::convert_back_amount_to_minor_units(
self.amount_converter,
amount.clone(),
data.request.currency,
@@ -393,7 +393,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);
let capture_amount_in_minor_units = match response.data.price_amount {
- Some(ref amount) => Some(utils::convert_back(
+ Some(ref amount) => Some(utils::convert_back_amount_to_minor_units(
self.amount_converter,
amount.clone(),
data.request.currency,
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 0874c3b7c54..ba17c44950c 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -827,13 +827,23 @@ impl
.parse_struct("PaymentIntentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response_integrity_object = connector_utils::get_sync_integrity_object(
+ self.amount_converter,
+ response.amount,
+ response.currency.clone(),
+ )?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
+ });
+ new_router_data.map(|mut router_data| {
+ router_data.request.integrity_object = Some(response_integrity_object);
+ router_data
})
}
Err(err) => {
@@ -1011,13 +1021,25 @@ impl
.parse_struct("ChargesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response_integrity_object =
+ connector_utils::get_authorise_integrity_object(
+ self.amount_converter,
+ response.amount,
+ response.currency.clone(),
+ )?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
+ });
+
+ new_router_data.map(|mut router_data| {
+ router_data.request.integrity_object = Some(response_integrity_object);
+ router_data
})
}
_ => {
@@ -1026,13 +1048,25 @@ impl
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response_integrity_object =
+ connector_utils::get_authorise_integrity_object(
+ self.amount_converter,
+ response.amount,
+ response.currency.clone(),
+ )?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
+ });
+
+ new_router_data.map(|mut router_data| {
+ router_data.request.integrity_object = Some(response_integrity_object);
+ router_data
})
}
},
@@ -1042,15 +1076,26 @@ impl
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response_integrity_object = connector_utils::get_authorise_integrity_object(
+ self.amount_converter,
+ response.amount,
+ response.currency.clone(),
+ )?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ .change_context(errors::ConnectorError::ResponseHandlingFailed);
+
+ new_router_data.map(|mut router_data| {
+ router_data.request.integrity_object = Some(response_integrity_object);
+ router_data
+ })
}
}
}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 5c01a483c89..5f2b18f0c0a 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1,4 +1,7 @@
-use std::collections::{HashMap, HashSet};
+use std::{
+ collections::{HashMap, HashSet},
+ str::FromStr,
+};
#[cfg(feature = "payouts")]
use api_models::payouts::{self, PayoutVendorAccountDetails};
@@ -17,7 +20,11 @@ use common_utils::{
};
use diesel_models::enums;
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::{mandates, payments::payment_attempt::PaymentAttempt};
+use hyperswitch_domain_models::{
+ mandates,
+ payments::payment_attempt::PaymentAttempt,
+ router_request_types::{AuthoriseIntegrityObject, SyncIntegrityObject},
+};
use masking::{ExposeInterface, Secret};
use once_cell::sync::Lazy;
use regex::Regex;
@@ -2863,7 +2870,7 @@ pub fn convert_amount<T>(
.change_context(errors::ConnectorError::AmountConversionFailed)
}
-pub fn convert_back<T>(
+pub fn convert_back_amount_to_minor_units<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: enums::Currency,
@@ -2872,3 +2879,36 @@ pub fn convert_back<T>(
.convert_back(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
+
+pub fn get_authorise_integrity_object<T>(
+ amount_convertor: &dyn AmountConvertor<Output = T>,
+ amount: T,
+ currency: String,
+) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> {
+ let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
+ .change_context(errors::ConnectorError::ParsingFailed)?;
+
+ let amount_in_minor_unit =
+ convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?;
+
+ Ok(AuthoriseIntegrityObject {
+ amount: amount_in_minor_unit,
+ currency: currency_enum,
+ })
+}
+
+pub fn get_sync_integrity_object<T>(
+ amount_convertor: &dyn AmountConvertor<Output = T>,
+ amount: T,
+ currency: String,
+) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> {
+ let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
+ .change_context(errors::ConnectorError::ParsingFailed)?;
+ let amount_in_minor_unit =
+ convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?;
+
+ Ok(SyncIntegrityObject {
+ amount: Some(amount_in_minor_unit),
+ currency: Some(currency_enum),
+ })
+}
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 5111ddcd15f..1be40a0ab6e 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -181,6 +181,7 @@ pub fn construct_router_data<F: Clone, Req, Res>(
refund_id: None,
payment_method_status: None,
connector_response: None,
+ integrity_check: Ok(()),
})
}
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 5ba901898f5..d897b9e6339 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -130,6 +130,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
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 5d2a86150c6..05aafb92f98 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -111,6 +111,7 @@ pub async fn construct_fulfillment_router_data<'a>(
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
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 5f2c3f39cc8..b44f2d3d4fc 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -102,6 +102,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
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 a0c773b7f4d..907b941ee67 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -111,6 +111,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
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 2cfa80eb80b..dd042a6b593 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -115,6 +115,7 @@ impl
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index e25c1ab9e7d..d158f173173 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -75,6 +75,7 @@ pub async fn construct_mandate_revoke_router_data(
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index c06d9a70e16..50cf31730a9 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -76,7 +76,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 resp = services::execute_connector_processing_step(
+ let mut new_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
@@ -86,8 +86,16 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
.await
.to_payment_failed_response()?;
+ // Initiating Integrity check
+ let integrity_result = helpers::check_integrity_based_on_flow(
+ &new_router_data.request,
+ &new_router_data.response,
+ );
+
+ new_router_data.integrity_check = integrity_result;
+
metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics
- Ok(resp)
+ Ok(new_router_data)
} else {
Ok(self.clone())
}
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index 5b0d1a48e67..336f73e99ed 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -85,7 +85,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>
(types::SyncRequestType::MultipleCaptureSync(_), Err(err)) => Err(err),
_ => {
// for bulk sync of captures, above logic needs to be handled at connector end
- let resp = services::execute_connector_processing_step(
+ let mut new_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
@@ -94,7 +94,16 @@ impl Feature<api::PSync, types::PaymentsSyncData>
)
.await
.to_payment_failed_response()?;
- Ok(resp)
+
+ // Initiating Integrity checks
+ let integrity_result = helpers::check_integrity_based_on_flow(
+ &new_router_data.request,
+ &new_router_data.response,
+ );
+
+ new_router_data.integrity_check = integrity_result;
+
+ Ok(new_router_data)
}
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 58f061115a1..534da72a1d9 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -21,6 +21,7 @@ use hyperswitch_domain_models::{
payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData, PaymentIntent},
router_data::KlarnaSdkResponse,
};
+use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject};
use josekit::jwe;
use masking::{ExposeInterface, PeekInterface};
use openssl::{
@@ -66,7 +67,7 @@ use crate::{
},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalPaymentMethodConnectorResponse, ErrorResponse, MandateReference,
- RecurringMandatePaymentData, RouterData,
+ PaymentsResponseData, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
@@ -3523,6 +3524,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
refund_id: router_data.refund_id,
dispute_id: router_data.dispute_id,
connector_response: router_data.connector_response,
+ integrity_check: Ok(()),
connector_wallets_details: router_data.connector_wallets_details,
}
}
@@ -4946,6 +4948,35 @@ pub fn get_redis_key_for_extended_card_info(merchant_id: &str, payment_id: &str)
format!("{merchant_id}_{payment_id}_extended_card_info")
}
+pub fn check_integrity_based_on_flow<T, Request>(
+ request: &Request,
+ payment_response_data: &Result<PaymentsResponseData, ErrorResponse>,
+) -> Result<(), common_utils::errors::IntegrityCheckError>
+where
+ T: FlowIntegrity,
+ Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
+{
+ let connector_transaction_id = match payment_response_data {
+ Ok(resp_data) => match resp_data {
+ PaymentsResponseData::TransactionResponse {
+ connector_response_reference_id,
+ ..
+ } => connector_response_reference_id,
+ PaymentsResponseData::TransactionUnresolvedResponse {
+ connector_response_reference_id,
+ ..
+ } => connector_response_reference_id,
+ PaymentsResponseData::PreProcessingResponse {
+ connector_response_reference_id,
+ ..
+ } => connector_response_reference_id,
+ _ => &None,
+ },
+ Err(_) => &None,
+ };
+ request.check_integrity(request, connector_transaction_id.to_owned())
+}
+
pub async fn config_skip_saving_wallet_at_connector(
db: &dyn StorageInterface,
merchant_id: &String,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 8fb0964da6e..a28b9fe3dd2 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -7,7 +7,7 @@ use 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 router_env::{instrument, logger, metrics::add_attributes, tracing};
use storage_impl::DataModelExt;
use tracing_futures::Instrument;
@@ -868,228 +868,271 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
};
(capture_update, attempt_update)
}
+
Ok(payments_response) => {
- let attempt_status = payment_data.payment_attempt.status.to_owned();
- let connector_status = router_data.status.to_owned();
- let updated_attempt_status = match (
- connector_status,
- attempt_status,
- payment_data.frm_message.to_owned(),
- ) {
- (
- enums::AttemptStatus::Authorized,
- enums::AttemptStatus::Unresolved,
- Some(frm_message),
- ) => match frm_message.frm_status {
- enums::FraudCheckStatus::Fraud | enums::FraudCheckStatus::ManualReview => {
- attempt_status
- }
- _ => router_data.get_attempt_status_for_db_update(&payment_data),
- },
- _ => router_data.get_attempt_status_for_db_update(&payment_data),
- };
- match payments_response {
- types::PaymentsResponseData::PreProcessingResponse {
- pre_processing_id,
- connector_metadata,
- connector_response_reference_id,
- ..
- } => {
- let connector_transaction_id = match pre_processing_id.to_owned() {
- types::PreprocessingResponseId::PreProcessingId(_) => None,
- types::PreprocessingResponseId::ConnectorTransactionId(
- connector_txn_id,
- ) => Some(connector_txn_id),
+ // match on connector integrity check
+ match router_data.integrity_check.clone() {
+ Err(err) => {
+ let auth_update = if Some(router_data.auth_type)
+ != payment_data.payment_attempt.authentication_type
+ {
+ Some(router_data.auth_type)
+ } else {
+ None
};
- let preprocessing_step_id = match pre_processing_id {
- types::PreprocessingResponseId::PreProcessingId(pre_processing_id) => {
- Some(pre_processing_id)
- }
- types::PreprocessingResponseId::ConnectorTransactionId(_) => None,
+ let field_name = err.field_names;
+ let connector_transaction_id = err.connector_transaction_id;
+ (
+ None,
+ Some(storage::PaymentAttemptUpdate::ErrorUpdate {
+ connector: None,
+ status: enums::AttemptStatus::Pending,
+ error_message: Some(Some("Integrity Check Failed!".to_string())),
+ error_code: Some(Some("IE".to_string())),
+ error_reason: Some(Some(format!(
+ "Integrity Check Failed! Value mismatched for fields {field_name}"
+ ))),
+ amount_capturable: None,
+ updated_by: storage_scheme.to_string(),
+ unified_code: None,
+ unified_message: None,
+ connector_transaction_id,
+ payment_method_data: None,
+ authentication_type: auth_update,
+ }),
+ )
+ }
+ Ok(()) => {
+ let attempt_status = payment_data.payment_attempt.status.to_owned();
+ let connector_status = router_data.status.to_owned();
+ let updated_attempt_status = match (
+ connector_status,
+ attempt_status,
+ payment_data.frm_message.to_owned(),
+ ) {
+ (
+ enums::AttemptStatus::Authorized,
+ enums::AttemptStatus::Unresolved,
+ Some(frm_message),
+ ) => match frm_message.frm_status {
+ enums::FraudCheckStatus::Fraud
+ | enums::FraudCheckStatus::ManualReview => attempt_status,
+ _ => router_data.get_attempt_status_for_db_update(&payment_data),
+ },
+ _ => router_data.get_attempt_status_for_db_update(&payment_data),
};
- let payment_attempt_update =
- storage::PaymentAttemptUpdate::PreprocessingUpdate {
- status: updated_attempt_status,
- payment_method_id: payment_data
- .payment_attempt
- .payment_method_id
- .clone(),
+ match payments_response {
+ types::PaymentsResponseData::PreProcessingResponse {
+ pre_processing_id,
+ connector_metadata,
+ connector_response_reference_id,
+ ..
+ } => {
+ let connector_transaction_id = match pre_processing_id.to_owned() {
+ types::PreprocessingResponseId::PreProcessingId(_) => None,
+ types::PreprocessingResponseId::ConnectorTransactionId(
+ connector_txn_id,
+ ) => Some(connector_txn_id),
+ };
+ let preprocessing_step_id = match pre_processing_id {
+ types::PreprocessingResponseId::PreProcessingId(
+ pre_processing_id,
+ ) => Some(pre_processing_id),
+ types::PreprocessingResponseId::ConnectorTransactionId(_) => None,
+ };
+ let payment_attempt_update =
+ storage::PaymentAttemptUpdate::PreprocessingUpdate {
+ status: updated_attempt_status,
+ payment_method_id: payment_data
+ .payment_attempt
+ .payment_method_id
+ .clone(),
+ connector_metadata,
+ preprocessing_step_id,
+ connector_transaction_id,
+ connector_response_reference_id,
+ updated_by: storage_scheme.to_string(),
+ };
+
+ (None, Some(payment_attempt_update))
+ }
+ types::PaymentsResponseData::TransactionResponse {
+ resource_id,
+ redirection_data,
connector_metadata,
- preprocessing_step_id,
- connector_transaction_id,
connector_response_reference_id,
- updated_by: storage_scheme.to_string(),
- };
-
- (None, Some(payment_attempt_update))
- }
- types::PaymentsResponseData::TransactionResponse {
- resource_id,
- redirection_data,
- connector_metadata,
- connector_response_reference_id,
- incremental_authorization_allowed,
- charge_id,
- ..
- } => {
- payment_data
- .payment_intent
- .incremental_authorization_allowed =
- core_utils::get_incremental_authorization_allowed_value(
incremental_authorization_allowed,
+ charge_id,
+ ..
+ } => {
payment_data
.payment_intent
- .request_incremental_authorization,
- );
- let connector_transaction_id = match resource_id {
- types::ResponseId::NoResponseId => None,
- types::ResponseId::ConnectorTransactionId(id)
- | types::ResponseId::EncodedData(id) => Some(id),
- };
-
- let encoded_data = payment_data.payment_attempt.encoded_data.clone();
+ .incremental_authorization_allowed =
+ core_utils::get_incremental_authorization_allowed_value(
+ incremental_authorization_allowed,
+ payment_data
+ .payment_intent
+ .request_incremental_authorization,
+ );
+ let connector_transaction_id = match resource_id {
+ types::ResponseId::NoResponseId => None,
+ types::ResponseId::ConnectorTransactionId(id)
+ | types::ResponseId::EncodedData(id) => Some(id),
+ };
- let authentication_data = redirection_data
- .as_ref()
- .map(Encode::encode_to_value)
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not parse the connector response")?;
+ let encoded_data = payment_data.payment_attempt.encoded_data.clone();
- let auth_update = if Some(router_data.auth_type)
- != payment_data.payment_attempt.authentication_type
- {
- Some(router_data.auth_type)
- } else {
- None
- };
+ let authentication_data = redirection_data
+ .as_ref()
+ .map(Encode::encode_to_value)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not parse the connector response")?;
- // incase of success, update error code and error message
- let error_status = if router_data.status == enums::AttemptStatus::Charged {
- Some(None)
- } else {
- None
- };
+ let auth_update = if Some(router_data.auth_type)
+ != payment_data.payment_attempt.authentication_type
+ {
+ Some(router_data.auth_type)
+ } else {
+ None
+ };
- if router_data.status == enums::AttemptStatus::Charged {
- payment_data
- .payment_intent
- .fingerprint_id
- .clone_from(&payment_data.payment_attempt.fingerprint_id);
- metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
- }
+ // incase of success, update error code and error message
+ let error_status =
+ if router_data.status == enums::AttemptStatus::Charged {
+ Some(None)
+ } else {
+ None
+ };
+
+ if router_data.status == enums::AttemptStatus::Charged {
+ payment_data
+ .payment_intent
+ .fingerprint_id
+ .clone_from(&payment_data.payment_attempt.fingerprint_id);
+ metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
+ }
- let payment_method_id = payment_data.payment_attempt.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,
+ router_data.apple_pay_flow.clone(),
+ payment_data.payment_attempt.connector.clone(),
+ payment_data.payment_attempt.merchant_id.clone(),
+ );
+ let (capture_updates, payment_attempt_update) = match payment_data
+ .multiple_capture_data
+ {
+ Some(multiple_capture_data) => {
+ let capture_update = storage::CaptureUpdate::ResponseUpdate {
+ status: enums::CaptureStatus::foreign_try_from(
+ router_data.status,
+ )?,
+ connector_capture_id: connector_transaction_id.clone(),
+ connector_response_reference_id,
+ };
+ let capture_update_list = vec![(
+ multiple_capture_data.get_latest_capture().clone(),
+ capture_update,
+ )];
+ (Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| {
+ storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
+ authentication_type: auth_type,
+ updated_by: storage_scheme.to_string(),
+ }
+ }))
+ }
+ None => (
+ None,
+ Some(storage::PaymentAttemptUpdate::ResponseUpdate {
+ status: updated_attempt_status,
+ connector: None,
+ connector_transaction_id: connector_transaction_id.clone(),
+ authentication_type: auth_update,
+ amount_capturable: router_data
+ .request
+ .get_amount_capturable(
+ &payment_data,
+ updated_attempt_status,
+ )
+ .map(MinorUnit::new),
+ payment_method_id,
+ mandate_id: payment_data.payment_attempt.mandate_id.clone(),
+ connector_metadata,
+ payment_token: None,
+ error_code: error_status.clone(),
+ error_message: error_status.clone(),
+ error_reason: error_status.clone(),
+ unified_code: error_status.clone(),
+ unified_message: error_status,
+ connector_response_reference_id,
+ updated_by: storage_scheme.to_string(),
+ authentication_data,
+ encoded_data,
+ payment_method_data: additional_payment_method_data,
+ charge_id,
+ }),
+ ),
+ };
- utils::add_apple_pay_payment_status_metrics(
- router_data.status,
- router_data.apple_pay_flow.clone(),
- payment_data.payment_attempt.connector.clone(),
- payment_data.payment_attempt.merchant_id.clone(),
- );
- let (capture_updates, payment_attempt_update) = match payment_data
- .multiple_capture_data
- {
- Some(multiple_capture_data) => {
- let capture_update = storage::CaptureUpdate::ResponseUpdate {
- status: enums::CaptureStatus::foreign_try_from(router_data.status)?,
- connector_capture_id: connector_transaction_id.clone(),
- connector_response_reference_id,
+ (capture_updates, payment_attempt_update)
+ }
+ types::PaymentsResponseData::TransactionUnresolvedResponse {
+ resource_id,
+ reason,
+ connector_response_reference_id,
+ } => {
+ let connector_transaction_id = match resource_id {
+ types::ResponseId::NoResponseId => None,
+ types::ResponseId::ConnectorTransactionId(id)
+ | types::ResponseId::EncodedData(id) => Some(id),
};
- let capture_update_list = vec![(
- multiple_capture_data.get_latest_capture().clone(),
- capture_update,
- )];
(
- Some((multiple_capture_data, capture_update_list)),
- auth_update.map(|auth_type| {
- storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
- authentication_type: auth_type,
- updated_by: storage_scheme.to_string(),
- }
+ None,
+ Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {
+ status: updated_attempt_status,
+ connector: None,
+ connector_transaction_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)),
+ connector_response_reference_id,
+ updated_by: storage_scheme.to_string(),
}),
)
}
- None => (
- None,
- Some(storage::PaymentAttemptUpdate::ResponseUpdate {
- status: updated_attempt_status,
- connector: None,
- connector_transaction_id: connector_transaction_id.clone(),
- authentication_type: auth_update,
- amount_capturable: router_data
- .request
- .get_amount_capturable(&payment_data, updated_attempt_status)
- .map(MinorUnit::new),
- payment_method_id,
- mandate_id: payment_data.payment_attempt.mandate_id.clone(),
- connector_metadata,
- payment_token: None,
- error_code: error_status.clone(),
- error_message: error_status.clone(),
- error_reason: error_status.clone(),
- unified_code: error_status.clone(),
- unified_message: error_status,
- connector_response_reference_id,
- updated_by: storage_scheme.to_string(),
- authentication_data,
- encoded_data,
- payment_method_data: additional_payment_method_data,
- charge_id,
- }),
- ),
- };
-
- (capture_updates, payment_attempt_update)
- }
- types::PaymentsResponseData::TransactionUnresolvedResponse {
- resource_id,
- reason,
- connector_response_reference_id,
- } => {
- let connector_transaction_id = match resource_id {
- types::ResponseId::NoResponseId => None,
- types::ResponseId::ConnectorTransactionId(id)
- | types::ResponseId::EncodedData(id) => Some(id),
- };
- (
- None,
- Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {
- status: updated_attempt_status,
- connector: None,
- connector_transaction_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)),
- connector_response_reference_id,
- updated_by: storage_scheme.to_string(),
- }),
- )
- }
- types::PaymentsResponseData::SessionResponse { .. } => (None, None),
- types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
- types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),
- types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None),
- types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None),
- types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => {
- (None, None)
- }
- types::PaymentsResponseData::MultipleCaptureResponse {
- capture_sync_response_list,
- } => match payment_data.multiple_capture_data {
- Some(multiple_capture_data) => {
- let capture_update_list = response_to_capture_update(
- &multiple_capture_data,
+ types::PaymentsResponseData::SessionResponse { .. } => (None, None),
+ types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
+ types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),
+ types::PaymentsResponseData::ConnectorCustomerResponse { .. } => {
+ (None, None)
+ }
+ types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {
+ (None, None)
+ }
+ types::PaymentsResponseData::IncrementalAuthorizationResponse {
+ ..
+ } => (None, None),
+ types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
- )?;
- (Some((multiple_capture_data, capture_update_list)), None)
+ } => match payment_data.multiple_capture_data {
+ Some(multiple_capture_data) => {
+ let capture_update_list = response_to_capture_update(
+ &multiple_capture_data,
+ capture_sync_response_list,
+ )?;
+ (Some((multiple_capture_data, capture_update_list)), None)
+ }
+ None => (None, None),
+ },
}
- None => (None, None),
- },
+ }
}
}
};
@@ -1308,7 +1351,33 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.as_mut()
.map(|info| info.status = status)
});
- Ok(payment_data)
+
+ match router_data.integrity_check {
+ Ok(()) => Ok(payment_data),
+ Err(err) => {
+ metrics::INTEGRITY_CHECK_FAILED.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([
+ (
+ "connector",
+ payment_data.payment_attempt.connector.unwrap_or_default(),
+ ),
+ ("merchant_id", payment_data.payment_attempt.merchant_id),
+ ]),
+ );
+ Err(error_stack::Report::new(
+ errors::ApiErrorResponse::IntegrityCheckFailed {
+ reason: payment_data
+ .payment_attempt
+ .error_message
+ .unwrap_or_default(),
+ field_names: err.field_names,
+ connector_transaction_id: payment_data.payment_attempt.connector_transaction_id,
+ },
+ ))
+ }
+ }
}
async fn update_payment_method_status_and_ntid<F: Clone>(
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 9fcce65fbaf..abcb4859710 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -195,6 +195,7 @@ where
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
@@ -1349,6 +1350,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.transpose()?,
customer_acceptance: payment_data.customer_acceptance,
charges,
+ integrity_object: None,
})
}
}
@@ -1358,7 +1360,14 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
+ let amount = payment_data
+ .surcharge_details
+ .as_ref()
+ .map(|surcharge_details| surcharge_details.final_amount)
+ .unwrap_or(payment_data.amount.into());
Ok(Self {
+ amount,
+ integrity_object: None,
mandate_id: payment_data.mandate_id.clone(),
connector_transaction_id: match payment_data.payment_attempt.connector_transaction_id {
Some(connector_txn_id) => {
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 7c7215b57cc..fffe039dab8 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -209,6 +209,7 @@ pub async fn construct_payout_router_data<'a, F>(
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
@@ -371,6 +372,7 @@ pub async fn construct_refund_router_data<'a, F>(
refund_id: Some(refund.refund_id.clone()),
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
@@ -608,6 +610,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
dispute_id: Some(dispute.dispute_id.clone()),
refund_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
@@ -703,6 +706,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
refund_id: None,
dispute_id: Some(dispute.dispute_id.clone()),
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
@@ -804,6 +808,7 @@ pub async fn construct_upload_file_router_data<'a>(
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
@@ -902,6 +907,7 @@ pub async fn construct_defend_dispute_router_data<'a>(
refund_id: None,
dispute_id: Some(dispute.dispute_id.clone()),
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
@@ -989,6 +995,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 3c96dcaf914..e0a0a86c78d 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -119,6 +119,7 @@ pub async fn construct_webhook_router_data<'a>(
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
};
Ok(router_data)
}
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 0d55a4b45c1..970ba5bd2de 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -131,3 +131,6 @@ 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);
+
+// A counter to indicate the integrity check failures
+counter_metric!(INTEGRITY_CHECK_FAILED, GLOBAL_METER);
diff --git a/crates/router/src/services/conversion_impls.rs b/crates/router/src/services/conversion_impls.rs
index d6b8e952b2d..741dabe7fac 100644
--- a/crates/router/src/services/conversion_impls.rs
+++ b/crates/router/src/services/conversion_impls.rs
@@ -71,6 +71,7 @@ fn get_default_router_data<F, Req, Resp>(
connector_response: None,
payment_method_status: None,
minor_amount_captured: None,
+ integrity_check: Ok(()),
}
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index f0087ef2f39..e6381e84b15 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -15,7 +15,6 @@ pub mod pm_auth;
pub mod storage;
pub mod transformers;
-
use std::marker::PhantomData;
pub use api_models::{enums::Connector, mandates};
@@ -790,6 +789,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
charges: None, // TODO: allow charges on mandates?
+ integrity_object: None,
}
}
}
@@ -843,6 +843,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
+ integrity_check: Ok(()),
}
}
}
@@ -904,6 +905,7 @@ impl<F1, F2>
refund_id: None,
dispute_id: None,
connector_response: data.connector_response.clone(),
+ integrity_check: Ok(()),
}
}
}
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 61db1792775..60b40e78663 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -55,6 +55,7 @@ impl VerifyConnectorData {
authentication_data: None,
customer_acceptance: None,
charges: None,
+ integrity_object: None,
}
}
@@ -110,6 +111,7 @@ impl VerifyConnectorData {
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
}
}
}
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 51bde094d64..d7eda4db835 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -122,6 +122,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
frm_metadata: None,
refund_id: None,
dispute_id: None,
+ integrity_check: Ok(()),
}
}
@@ -186,6 +187,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
frm_metadata: None,
refund_id: None,
dispute_id: None,
+ integrity_check: Ok(()),
}
}
diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs
index 67cd9702319..a4cb9b4c5e0 100644
--- a/crates/router/tests/connectors/bambora.rs
+++ b/crates/router/tests/connectors/bambora.rs
@@ -1,5 +1,6 @@
use std::str::FromStr;
+use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums};
@@ -111,6 +112,8 @@ async fn should_sync_authorized_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ integrity_object: None,
+ amount: MinorUnit::new(100),
}),
None,
)
@@ -228,6 +231,8 @@ async fn should_sync_auto_captured_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ integrity_object: None,
+ amount: MinorUnit::new(100),
}),
None,
)
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index ef43b3ca8b4..45a30614bfa 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -1,6 +1,7 @@
use std::{str::FromStr, time::Duration};
use cards::CardNumber;
+use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, api, domain, storage::enums};
@@ -160,6 +161,8 @@ async fn should_sync_authorized_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ integrity_object: None,
+ amount: MinorUnit::new(100),
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs
index 8e98702c796..7909aa9c7fc 100644
--- a/crates/router/tests/connectors/nexinets.rs
+++ b/crates/router/tests/connectors/nexinets.rs
@@ -1,6 +1,7 @@
use std::str::FromStr;
use cards::CardNumber;
+use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums, PaymentsAuthorizeData};
@@ -127,6 +128,8 @@ async fn should_sync_authorized_payment() {
payment_method_type: None,
currency: enums::Currency::EUR,
payment_experience: None,
+ integrity_object: None,
+ amount: MinorUnit::new(100),
}),
None,
)
diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs
index 0b3d040838b..8de891ef09d 100644
--- a/crates/router/tests/connectors/paypal.rs
+++ b/crates/router/tests/connectors/paypal.rs
@@ -1,5 +1,6 @@
use std::str::FromStr;
+use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType};
@@ -144,6 +145,8 @@ async fn should_sync_authorized_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ integrity_object: None,
+ amount: MinorUnit::new(100),
}),
get_default_payment_info(),
)
@@ -343,6 +346,8 @@ async fn should_sync_auto_captured_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ amount: MinorUnit::new(100),
+ integrity_object: None,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index a9ffdbe6974..53bbea865c2 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -538,6 +538,7 @@ pub trait ConnectorActions: Connector {
refund_id: None,
dispute_id: None,
connector_response: None,
+ integrity_check: Ok(()),
}
}
@@ -935,6 +936,7 @@ impl Default for PaymentAuthorizeType {
authentication_data: None,
customer_acceptance: None,
charges: None,
+ integrity_object: None,
};
Self(data)
}
@@ -994,6 +996,8 @@ impl Default for PaymentSyncType {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ amount: MinorUnit::new(100),
+ integrity_object: None,
};
Self(data)
}
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index 3dc7b819a93..2b9ea8f8211 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -2,7 +2,7 @@ use std::str::FromStr;
use api_models::payments::OrderDetailsWithAmount;
use cards::CardNumber;
-use common_utils::pii::Email;
+use common_utils::{pii::Email, types::MinorUnit};
use masking::Secret;
use router::types::{self, domain, storage::enums};
@@ -106,6 +106,8 @@ async fn should_sync_authorized_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ amount: MinorUnit::new(100),
+ integrity_object: None,
}),
None,
)
@@ -223,6 +225,8 @@ async fn should_sync_auto_captured_payment() {
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
+ amount: MinorUnit::new(100),
+ integrity_object: None,
}),
None,
)
|
feat
|
Added integrity framework for Authorize and Sync flow with connector as Stripe (#5109)
|
f3baf2ff3f0a50a5558316625ade647e7607d6c2
|
2023-07-25 12:37:35
|
Sanchith Hegde
|
feat(db): implement `MerchantKeyStoreInterface` for `MockDb` (#1772)
| false
|
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 304e2a0fc74..caf6264db61 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -120,6 +120,7 @@ pub struct MockDb {
disputes: Arc<Mutex<Vec<storage::Dispute>>>,
lockers: Arc<Mutex<Vec<storage::LockerMockUp>>>,
mandates: Arc<Mutex<Vec<storage::Mandate>>>,
+ merchant_key_store: Arc<Mutex<Vec<storage::MerchantKeyStore>>>,
}
impl MockDb {
@@ -144,6 +145,7 @@ impl MockDb {
disputes: Default::default(),
lockers: Default::default(),
mandates: Default::default(),
+ merchant_key_store: Default::default(),
}
}
}
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 973b18de880..6c47fb7f5d6 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -667,6 +667,8 @@ mod merchant_connector_account_cache_tests {
use common_utils::date_time;
use diesel_models::enums::ConnectorType;
use error_stack::ResultExt;
+ use masking::PeekInterface;
+ use time::macros::datetime;
use crate::{
cache::{CacheKind, ACCOUNTS_CACHE},
@@ -675,7 +677,7 @@ mod merchant_connector_account_cache_tests {
cache, merchant_connector_account::MerchantConnectorAccountInterface,
merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb,
},
- services::{PubSubInterface, RedisConnInterface},
+ services::{self, PubSubInterface, RedisConnInterface},
types::{
domain::{self, behaviour::Conversion, types as domain_types},
storage,
@@ -684,12 +686,11 @@ mod merchant_connector_account_cache_tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
- #[ignore = "blocked on MockDb implementation of merchant key store"]
async fn test_connector_label_cache() {
let db = MockDb::new(&Default::default()).await;
let redis_conn = db.get_redis_conn();
- let key = db.get_master_key();
+ let master_key = db.get_master_key();
redis_conn
.subscribe("hyperswitch_invalidate")
.await
@@ -699,13 +700,34 @@ mod merchant_connector_account_cache_tests {
let connector_label = "stripe_USA";
let merchant_connector_id = "simple_merchant_connector_id";
+ db.insert_merchant_key_store(
+ domain::MerchantKeyStore {
+ merchant_id: merchant_id.into(),
+ key: domain_types::encrypt(
+ services::generate_aes256_key().unwrap().to_vec().into(),
+ master_key,
+ )
+ .await
+ .unwrap(),
+ created_at: datetime!(2023-02-01 0:00),
+ },
+ &master_key.to_vec().into(),
+ )
+ .await
+ .unwrap();
+
+ let merchant_key = db
+ .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into())
+ .await
+ .unwrap();
+
let mca = domain::MerchantConnectorAccount {
id: Some(1),
merchant_id: merchant_id.to_string(),
connector_name: "stripe".to_string(),
connector_account_details: domain_types::encrypt(
serde_json::Value::default().into(),
- key,
+ merchant_key.key.get_inner().peek(),
)
.await
.unwrap(),
@@ -725,19 +747,14 @@ mod merchant_connector_account_cache_tests {
connector_webhook_details: None,
};
- let key_store = db
- .get_merchant_key_store_by_merchant_id(merchant_id, &key.to_vec().into())
- .await
- .unwrap();
-
- db.insert_merchant_connector_account(mca, &key_store)
+ db.insert_merchant_connector_account(mca, &merchant_key)
.await
.unwrap();
let find_call = || async {
db.find_merchant_connector_account_by_merchant_id_connector_label(
merchant_id,
connector_label,
- &key_store,
+ &merchant_key,
)
.await
.unwrap()
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index 0dfbce05422..32bf9f4270b 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -49,6 +49,7 @@ impl MerchantKeyStoreInterface for Store {
.await
.change_context(errors::StorageError::DecryptionError)
}
+
async fn get_merchant_key_store_by_merchant_id(
&self,
merchant_id: &str,
@@ -95,18 +96,119 @@ impl MerchantKeyStoreInterface for Store {
impl MerchantKeyStoreInterface for MockDb {
async fn insert_merchant_key_store(
&self,
- _merchant_key_store: domain::MerchantKeyStore,
- _key: &Secret<Vec<u8>>,
+ merchant_key_store: domain::MerchantKeyStore,
+ key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError.into())
+ let mut locked_merchant_key_store = self.merchant_key_store.lock().await;
+
+ if locked_merchant_key_store
+ .iter()
+ .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "merchant_key_store",
+ key: Some(merchant_key_store.merchant_id.clone()),
+ })?;
+ }
+
+ let merchant_key = Conversion::convert(merchant_key_store)
+ .await
+ .change_context(errors::StorageError::MockDbError)?;
+ locked_merchant_key_store.push(merchant_key.clone());
+
+ merchant_key
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
+
async fn get_merchant_key_store_by_merchant_id(
&self,
- _merchant_id: &str,
- _key: &Secret<Vec<u8>>,
+ merchant_id: &str,
+ key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
- // [#172]: Implement function for `MockDb`
- Err(errors::StorageError::MockDbError.into())
+ self.merchant_key_store
+ .lock()
+ .await
+ .iter()
+ .find(|merchant_key| merchant_key.merchant_id == merchant_id)
+ .cloned()
+ .ok_or(errors::StorageError::ValueNotFound(String::from(
+ "merchant_key_store",
+ )))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use time::macros::datetime;
+
+ use crate::{
+ db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb},
+ services,
+ types::domain::{self, types as domain_types},
+ };
+
+ #[allow(clippy::unwrap_used)]
+ #[tokio::test]
+ async fn test_mock_db_merchant_key_store_interface() {
+ let mock_db = MockDb::new(&Default::default()).await;
+ let master_key = mock_db.get_master_key();
+ let merchant_id = "merchant1";
+
+ let merchant_key1 = mock_db
+ .insert_merchant_key_store(
+ domain::MerchantKeyStore {
+ merchant_id: merchant_id.into(),
+ key: domain_types::encrypt(
+ services::generate_aes256_key().unwrap().to_vec().into(),
+ master_key,
+ )
+ .await
+ .unwrap(),
+ created_at: datetime!(2023-02-01 0:00),
+ },
+ &master_key.to_vec().into(),
+ )
+ .await
+ .unwrap();
+
+ let found_merchant_key1 = mock_db
+ .get_merchant_key_store_by_merchant_id(merchant_id, &master_key.to_vec().into())
+ .await
+ .unwrap();
+
+ assert_eq!(found_merchant_key1.merchant_id, merchant_key1.merchant_id);
+ assert_eq!(found_merchant_key1.key, merchant_key1.key);
+
+ let insert_duplicate_merchant_key1_result = mock_db
+ .insert_merchant_key_store(
+ domain::MerchantKeyStore {
+ merchant_id: merchant_id.into(),
+ key: domain_types::encrypt(
+ services::generate_aes256_key().unwrap().to_vec().into(),
+ master_key,
+ )
+ .await
+ .unwrap(),
+ created_at: datetime!(2023-02-01 0:00),
+ },
+ &master_key.to_vec().into(),
+ )
+ .await;
+ assert!(insert_duplicate_merchant_key1_result.is_err());
+
+ let find_non_existent_merchant_key_result = mock_db
+ .get_merchant_key_store_by_merchant_id("non_existent", &master_key.to_vec().into())
+ .await;
+ assert!(find_non_existent_merchant_key_result.is_err());
+
+ let find_merchant_key_with_incorrect_master_key_result = mock_db
+ .get_merchant_key_store_by_merchant_id(merchant_id, &vec![0; 32].into())
+ .await;
+ assert!(find_merchant_key_with_incorrect_master_key_result.is_err());
}
}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 396315b4c85..0b66ac7d8a0 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -9,28 +9,27 @@ pub mod enums;
pub mod ephemeral_key;
pub mod events;
pub mod file;
+#[cfg(feature = "kv_store")]
+pub mod kv;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
+pub mod merchant_key_store;
pub mod payment_attempt;
pub mod payment_intent;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod process_tracker;
-pub mod reverse_lookup;
-
mod query;
pub mod refund;
-
-#[cfg(feature = "kv_store")]
-pub mod kv;
+pub mod reverse_lookup;
pub use self::{
address::*, api_keys::*, cards_info::*, configs::*, connector_response::*, customers::*,
dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*,
- merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*,
- payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*,
- reverse_lookup::*,
+ merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_attempt::*,
+ payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*,
+ refund::*, reverse_lookup::*,
};
diff --git a/crates/router/src/types/storage/merchant_key_store.rs b/crates/router/src/types/storage/merchant_key_store.rs
new file mode 100644
index 00000000000..29371aed08f
--- /dev/null
+++ b/crates/router/src/types/storage/merchant_key_store.rs
@@ -0,0 +1 @@
+pub use diesel_models::merchant_key_store::MerchantKeyStore;
|
feat
|
implement `MerchantKeyStoreInterface` for `MockDb` (#1772)
|
3db5b82d0de45130695e1a47b9e71473020fd84d
|
2024-05-08 13:47:50
|
Mani Chandra
|
fix(users): Correct the condition for `verify_email` flow in decision manger (#4580)
| false
|
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
|
fix
|
Correct the condition for `verify_email` flow in decision manger (#4580)
|
d6b0660569eb8bbbc6557aa6ed29184fe51ab209
|
2025-01-21 12:49:48
|
Kashif
|
feat(connectors): fiuu,novalnet,worldpay - extend NTI flows (#6946)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 821e854c9fa..c860420da38 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -802,7 +802,7 @@ check_token_status_url= "" # base url to check token status from token servic
connector_list = "cybersource" # Supported connectors for network tokenization
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource" # Supported connectors for network transaction id
+connector_list = "adyen,cybersource,novalnet,stripe,worldpay" # Supported connectors for network transaction id
[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration
host = "localhost" # Client Host
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 6283382258a..b6e487e5a3b 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -191,7 +191,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup
card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource"
+connector_list = "adyen,cybersource,novalnet,stripe,worldpay"
[payouts]
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index fcfadb339d9..7242f263672 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -191,7 +191,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup
card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource"
+connector_list = "adyen,cybersource,novalnet,stripe,worldpay"
[payouts]
diff --git a/config/development.toml b/config/development.toml
index 08520a2a859..a32102aeebf 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -653,7 +653,7 @@ card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource"
+connector_list = "adyen,cybersource,novalnet,stripe,worldpay"
[connector_request_reference_id_config]
merchant_ids_send_payment_id_as_connector_request_id = []
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 6f95380d2db..cfdf4b0e0c2 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -540,7 +540,7 @@ card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource"
+connector_list = "adyen,cybersource,novalnet,stripe,worldpay"
[connector_customer]
connector_list = "gocardless,stax,stripe"
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu.rs b/crates/hyperswitch_connectors/src/connectors/fiuu.rs
index 3ea8793d9f5..70bca41582c 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu.rs
@@ -254,16 +254,23 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let url = if req.request.off_session == Some(true) {
- format!(
+ let optional_is_mit_flow = req.request.off_session;
+ let optional_is_nti_flow = req
+ .request
+ .mandate_id
+ .as_ref()
+ .map(|mandate_id| mandate_id.is_network_transaction_id_flow());
+ let url = match (optional_is_mit_flow, optional_is_nti_flow) {
+ (Some(true), Some(false)) => format!(
"{}/RMS/API/Recurring/input_v7.php",
self.base_url(connectors)
- )
- } else {
- format!(
- "{}RMS/API/Direct/1.4.0/index.php",
- self.base_url(connectors)
- )
+ ),
+ _ => {
+ format!(
+ "{}RMS/API/Direct/1.4.0/index.php",
+ self.base_url(connectors)
+ )
+ }
};
Ok(url)
}
@@ -280,14 +287,24 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
)?;
let connector_router_data = fiuu::FiuuRouterData::from((amount, req));
- let connector_req = if req.request.off_session == Some(true) {
- let recurring_request = fiuu::FiuuMandateRequest::try_from(&connector_router_data)?;
- build_form_from_struct(recurring_request)
- .change_context(errors::ConnectorError::ParsingFailed)?
- } else {
- let payment_request = fiuu::FiuuPaymentRequest::try_from(&connector_router_data)?;
- build_form_from_struct(payment_request)
- .change_context(errors::ConnectorError::ParsingFailed)?
+ let optional_is_mit_flow = req.request.off_session;
+ let optional_is_nti_flow = req
+ .request
+ .mandate_id
+ .as_ref()
+ .map(|mandate_id| mandate_id.is_network_transaction_id_flow());
+
+ let connector_req = match (optional_is_mit_flow, optional_is_nti_flow) {
+ (Some(true), Some(false)) => {
+ let recurring_request = fiuu::FiuuMandateRequest::try_from(&connector_router_data)?;
+ build_form_from_struct(recurring_request)
+ .change_context(errors::ConnectorError::ParsingFailed)?
+ }
+ _ => {
+ let payment_request = fiuu::FiuuPaymentRequest::try_from(&connector_router_data)?;
+ build_form_from_struct(payment_request)
+ .change_context(errors::ConnectorError::ParsingFailed)?
+ }
};
Ok(RequestContent::FormData(connector_req))
}
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index e914454e557..51fc23eee41 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -14,8 +14,8 @@ use common_utils::{
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{
- BankRedirectData, Card, GooglePayWalletData, PaymentMethodData, RealTimePaymentData,
- WalletData,
+ BankRedirectData, Card, CardDetailsForNetworkTransactionId, GooglePayWalletData,
+ PaymentMethodData, RealTimePaymentData, WalletData,
},
router_data::{
ApplePayPredecryptData, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData,
@@ -287,6 +287,7 @@ pub struct FiuuPaymentRequest {
pub enum FiuuPaymentMethodData {
FiuuQRData(Box<FiuuQRData>),
FiuuCardData(Box<FiuuCardData>),
+ FiuuCardWithNTI(Box<FiuuCardWithNTI>),
FiuuFpxData(Box<FiuuFPXData>),
FiuuGooglePayData(Box<FiuuGooglePayData>),
FiuuApplePayData(Box<FiuuApplePayData>),
@@ -322,6 +323,18 @@ pub struct FiuuCardData {
customer_email: Option<Email>,
}
+#[derive(Serialize, Debug, Clone)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub struct FiuuCardWithNTI {
+ #[serde(rename = "TxnChannel")]
+ txn_channel: TxnChannel,
+ cc_pan: CardNumber,
+ cc_month: Secret<String>,
+ cc_year: Secret<String>,
+ #[serde(rename = "OriginalSchemeID")]
+ original_scheme_id: Secret<String>,
+}
+
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct FiuuApplePayData {
@@ -412,125 +425,150 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque
Url::parse(&item.router_data.request.get_webhook_url()?)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
);
- let payment_method_data = match item.router_data.request.payment_method_data {
- PaymentMethodData::Card(ref card) => {
- FiuuPaymentMethodData::try_from((card, item.router_data))
- }
- PaymentMethodData::RealTimePayment(ref real_time_payment_data) => {
- match *real_time_payment_data.clone() {
- RealTimePaymentData::DuitNow {} => {
- Ok(FiuuPaymentMethodData::FiuuQRData(Box::new(FiuuQRData {
- txn_channel: TxnChannel::RppDuitNowQr,
+ let payment_method_data = match item
+ .router_data
+ .request
+ .mandate_id
+ .clone()
+ .and_then(|mandate_id| mandate_id.mandate_reference_id)
+ {
+ None => match item.router_data.request.payment_method_data {
+ PaymentMethodData::Card(ref card) => {
+ FiuuPaymentMethodData::try_from((card, item.router_data))
+ }
+ PaymentMethodData::RealTimePayment(ref real_time_payment_data) => {
+ match *real_time_payment_data.clone() {
+ RealTimePaymentData::DuitNow {} => {
+ Ok(FiuuPaymentMethodData::FiuuQRData(Box::new(FiuuQRData {
+ txn_channel: TxnChannel::RppDuitNowQr,
+ })))
+ }
+ RealTimePaymentData::Fps {}
+ | RealTimePaymentData::PromptPay {}
+ | RealTimePaymentData::VietQr {} => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("fiuu"),
+ )
+ .into())
+ }
+ }
+ }
+ PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data
+ {
+ BankRedirectData::OnlineBankingFpx { ref issuer } => {
+ Ok(FiuuPaymentMethodData::FiuuFpxData(Box::new(FiuuFPXData {
+ txn_channel: FPXTxnChannel::try_from(*issuer)?,
+ non_3ds,
})))
}
- RealTimePaymentData::Fps {}
- | RealTimePaymentData::PromptPay {}
- | RealTimePaymentData::VietQr {} => {
+ BankRedirectData::BancontactCard { .. }
+ | BankRedirectData::Bizum {}
+ | BankRedirectData::Blik { .. }
+ | BankRedirectData::Eps { .. }
+ | BankRedirectData::Giropay { .. }
+ | BankRedirectData::Ideal { .. }
+ | BankRedirectData::Interac { .. }
+ | BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | BankRedirectData::OnlineBankingFinland { .. }
+ | BankRedirectData::OnlineBankingPoland { .. }
+ | BankRedirectData::OnlineBankingSlovakia { .. }
+ | BankRedirectData::OpenBankingUk { .. }
+ | BankRedirectData::Przelewy24 { .. }
+ | BankRedirectData::Sofort { .. }
+ | BankRedirectData::Trustly { .. }
+ | BankRedirectData::OnlineBankingThailand { .. }
+ | BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
- }
- }
- PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data {
- BankRedirectData::OnlineBankingFpx { ref issuer } => {
- Ok(FiuuPaymentMethodData::FiuuFpxData(Box::new(FiuuFPXData {
- txn_channel: FPXTxnChannel::try_from(*issuer)?,
- non_3ds,
- })))
- }
- BankRedirectData::BancontactCard { .. }
- | BankRedirectData::Bizum {}
- | BankRedirectData::Blik { .. }
- | BankRedirectData::Eps { .. }
- | BankRedirectData::Giropay { .. }
- | BankRedirectData::Ideal { .. }
- | BankRedirectData::Interac { .. }
- | BankRedirectData::OnlineBankingCzechRepublic { .. }
- | BankRedirectData::OnlineBankingFinland { .. }
- | BankRedirectData::OnlineBankingPoland { .. }
- | BankRedirectData::OnlineBankingSlovakia { .. }
- | BankRedirectData::OpenBankingUk { .. }
- | BankRedirectData::Przelewy24 { .. }
- | BankRedirectData::Sofort { .. }
- | BankRedirectData::Trustly { .. }
- | BankRedirectData::OnlineBankingThailand { .. }
- | BankRedirectData::LocalBankRedirect {} => {
+ },
+ PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
+ WalletData::GooglePay(google_pay_data) => {
+ FiuuPaymentMethodData::try_from(google_pay_data)
+ }
+ WalletData::ApplePay(_apple_pay_data) => {
+ let payment_method_token = item.router_data.get_payment_method_token()?;
+ match payment_method_token {
+ PaymentMethodToken::Token(_) => {
+ Err(unimplemented_payment_method!("Apple Pay", "Manual", "Fiuu"))?
+ }
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ FiuuPaymentMethodData::try_from(decrypt_data)
+ }
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Fiuu"))?
+ }
+ }
+ }
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("fiuu"),
+ )
+ .into()),
+ },
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Reward
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiuu"),
)
.into())
}
},
- PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
- WalletData::GooglePay(google_pay_data) => {
- FiuuPaymentMethodData::try_from(google_pay_data)
- }
- WalletData::ApplePay(_apple_pay_data) => {
- let payment_method_token = item.router_data.get_payment_method_token()?;
- match payment_method_token {
- PaymentMethodToken::Token(_) => {
- Err(unimplemented_payment_method!("Apple Pay", "Manual", "Fiuu"))?
- }
- PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- FiuuPaymentMethodData::try_from(decrypt_data)
- }
- PaymentMethodToken::PazeDecrypt(_) => {
- Err(unimplemented_payment_method!("Paze", "Fiuu"))?
- }
+ // Card payments using network transaction ID
+ Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
+ match item.router_data.request.payment_method_data {
+ PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => {
+ FiuuPaymentMethodData::try_from((raw_card_details, network_transaction_id))
}
+ _ => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("fiuu"),
+ )
+ .into()),
}
- WalletData::AliPayQr(_)
- | WalletData::AliPayRedirect(_)
- | WalletData::AliPayHkRedirect(_)
- | WalletData::MomoRedirect(_)
- | WalletData::KakaoPayRedirect(_)
- | WalletData::GoPayRedirect(_)
- | WalletData::GcashRedirect(_)
- | WalletData::ApplePayRedirect(_)
- | WalletData::ApplePayThirdPartySdk(_)
- | WalletData::DanaRedirect {}
- | WalletData::GooglePayRedirect(_)
- | WalletData::GooglePayThirdPartySdk(_)
- | WalletData::MbWayRedirect(_)
- | WalletData::MobilePayRedirect(_)
- | WalletData::PaypalRedirect(_)
- | WalletData::PaypalSdk(_)
- | WalletData::Paze(_)
- | WalletData::SamsungPay(_)
- | WalletData::TwintRedirect {}
- | WalletData::VippsRedirect {}
- | WalletData::TouchNGoRedirect(_)
- | WalletData::WeChatPayRedirect(_)
- | WalletData::WeChatPayQr(_)
- | WalletData::CashappQr(_)
- | WalletData::SwishQr(_)
- | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("fiuu"),
- )
- .into()),
- },
- PaymentMethodData::CardRedirect(_)
- | PaymentMethodData::PayLater(_)
- | PaymentMethodData::BankDebit(_)
- | PaymentMethodData::BankTransfer(_)
- | PaymentMethodData::Crypto(_)
- | PaymentMethodData::MandatePayment
- | PaymentMethodData::MobilePayment(_)
- | PaymentMethodData::Reward
- | PaymentMethodData::Upi(_)
- | PaymentMethodData::Voucher(_)
- | PaymentMethodData::GiftCard(_)
- | PaymentMethodData::CardToken(_)
- | PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::NetworkToken(_)
- | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("fiuu"),
- )
- .into())
}
+ _ => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("fiuu"),
+ )
+ .into()),
}?;
Ok(Self {
@@ -556,7 +594,7 @@ impl TryFrom<(&Card, &PaymentsAuthorizeRouterData)> for FiuuPaymentMethodData {
if item.request.is_customer_initiated_mandate_payment() {
(Some(1), Some(item.get_billing_email()?))
} else {
- (None, None)
+ (Some(3), None)
};
let non_3ds = match item.is_three_ds() {
false => 1,
@@ -575,6 +613,21 @@ impl TryFrom<(&Card, &PaymentsAuthorizeRouterData)> for FiuuPaymentMethodData {
}
}
+impl TryFrom<(&CardDetailsForNetworkTransactionId, String)> for FiuuPaymentMethodData {
+ type Error = Report<errors::ConnectorError>;
+ fn try_from(
+ (raw_card_data, network_transaction_id): (&CardDetailsForNetworkTransactionId, String),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self::FiuuCardWithNTI(Box::new(FiuuCardWithNTI {
+ txn_channel: TxnChannel::Creditan,
+ cc_pan: raw_card_data.card_number.clone(),
+ cc_month: raw_card_data.card_exp_month.clone(),
+ cc_year: raw_card_data.card_exp_year.clone(),
+ original_scheme_id: Secret::new(network_transaction_id),
+ })))
+ }
+}
+
impl TryFrom<&GooglePayWalletData> for FiuuPaymentMethodData {
type Error = Report<errors::ConnectorError>;
fn try_from(data: &GooglePayWalletData) -> Result<Self, Self::Error> {
@@ -1092,6 +1145,8 @@ pub struct FiuuPaymentSyncResponse {
error_desc: String,
#[serde(rename = "miscellaneous")]
miscellaneous: Option<HashMap<String, Secret<String>>>,
+ #[serde(rename = "SchemeTransactionID")]
+ scheme_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Display, Clone, PartialEq)]
@@ -1183,7 +1238,10 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
- network_txn_id: None,
+ network_txn_id: response
+ .scheme_transaction_id
+ .as_ref()
+ .map(|id| id.clone().expose()),
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charge_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
index d62d3d2a755..6d3199ecf1a 100644
--- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
@@ -102,6 +102,13 @@ pub struct NovalnetCard {
card_holder: Secret<String>,
}
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct NovalnetRawCardDetails {
+ card_number: CardNumber,
+ card_expiry_month: Secret<String>,
+ card_expiry_year: Secret<String>,
+}
+
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetMandate {
token: Secret<String>,
@@ -121,6 +128,7 @@ pub struct NovalnetApplePay {
#[serde(untagged)]
pub enum NovalNetPaymentData {
Card(NovalnetCard),
+ RawCardForNTI(NovalnetRawCardDetails),
GooglePay(NovalnetGooglePay),
ApplePay(NovalnetApplePay),
MandatePayment(NovalnetMandate),
@@ -151,6 +159,7 @@ pub struct NovalnetPaymentsRequestTransaction {
error_return_url: Option<String>,
enforce_3d: Option<i8>, //NOTE: Needed for CREDITCARD, GOOGLEPAY
create_token: Option<i8>,
+ scheme_tid: Option<Secret<String>>, // Card network's transaction ID
}
#[derive(Debug, Serialize, Clone)]
@@ -261,6 +270,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
+ scheme_tid: None,
};
Ok(Self {
@@ -292,6 +302,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
payment_data: Some(novalnet_google_pay),
enforce_3d,
create_token,
+ scheme_tid: None,
};
Ok(Self {
@@ -317,6 +328,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
})),
enforce_3d: None,
create_token,
+ scheme_tid: None,
};
Ok(Self {
@@ -358,6 +370,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
payment_data: None,
enforce_3d: None,
create_token,
+ scheme_tid: None,
};
Ok(Self {
merchant,
@@ -416,6 +429,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
payment_data: Some(novalnet_mandate_data),
enforce_3d,
create_token: None,
+ scheme_tid: None,
};
Ok(Self {
@@ -425,6 +439,44 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym
custom,
})
}
+ Some(api_models::payments::MandateReferenceId::NetworkMandateId(
+ network_transaction_id,
+ )) => match item.router_data.request.payment_method_data {
+ PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => {
+ let novalnet_card =
+ NovalNetPaymentData::RawCardForNTI(NovalnetRawCardDetails {
+ card_number: raw_card_details.card_number.clone(),
+ card_expiry_month: raw_card_details.card_exp_month.clone(),
+ card_expiry_year: raw_card_details.card_exp_year.clone(),
+ });
+
+ let transaction = NovalnetPaymentsRequestTransaction {
+ test_mode,
+ payment_type: NovalNetPaymentTypes::CREDITCARD,
+ amount: NovalNetAmount::StringMinor(item.amount.clone()),
+ currency: item.router_data.request.currency,
+ order_no: item.router_data.connector_request_reference_id.clone(),
+ hook_url: Some(hook_url),
+ return_url: Some(return_url.clone()),
+ error_return_url: Some(return_url.clone()),
+ payment_data: Some(novalnet_card),
+ enforce_3d,
+ create_token,
+ scheme_tid: Some(network_transaction_id.into()),
+ };
+
+ Ok(Self {
+ merchant,
+ transaction,
+ customer,
+ custom,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("novalnet"),
+ )
+ .into()),
+ },
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
@@ -1466,6 +1518,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest {
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
+ scheme_tid: None,
};
Ok(Self {
@@ -1495,6 +1548,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest {
payment_data: Some(novalnet_google_pay),
enforce_3d,
create_token,
+ scheme_tid: None,
};
Ok(Self {
@@ -1519,6 +1573,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest {
})),
enforce_3d: None,
create_token,
+ scheme_tid: None,
};
Ok(Self {
@@ -1559,7 +1614,9 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest {
payment_data: None,
enforce_3d: None,
create_token,
+ scheme_tid: None,
};
+
Ok(Self {
merchant,
transaction,
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs
index 07e4c178f9b..104e854e6fe 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs
@@ -1199,6 +1199,42 @@ impl IncomingWebhook for Worldpay {
let psync_body = WorldpayEventResponse::try_from(body)?;
Ok(Box::new(psync_body))
}
+
+ fn get_mandate_details(
+ &self,
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
+ errors::ConnectorError,
+ > {
+ let body: WorldpayWebhookTransactionId = request
+ .body
+ .parse_struct("WorldpayWebhookTransactionId")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+ let mandate_reference = body.event_details.token.map(|mandate_token| {
+ hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails {
+ connector_mandate_id: mandate_token.href,
+ }
+ });
+ Ok(mandate_reference)
+ }
+
+ fn get_network_txn_id(
+ &self,
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
+ errors::ConnectorError,
+ > {
+ let body: WorldpayWebhookTransactionId = request
+ .body
+ .parse_struct("WorldpayWebhookTransactionId")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+ let optional_network_txn_id = body.event_details.scheme_reference.map(|network_txn_id| {
+ hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId::new(network_txn_id)
+ });
+ Ok(optional_network_txn_id)
+ }
}
impl ConnectorRedirectResponse for Worldpay {
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
index 884caa9e840..52ae2c4f16f 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
@@ -52,18 +52,22 @@ pub enum TokenCreationType {
Worldpay,
}
+#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerAgreement {
#[serde(rename = "type")]
pub agreement_type: CustomerAgreementType,
- pub stored_card_usage: StoredCardUsageType,
+ pub stored_card_usage: Option<StoredCardUsageType>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scheme_reference: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CustomerAgreementType {
Subscription,
+ Unscheduled,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
@@ -78,6 +82,7 @@ pub enum StoredCardUsageType {
pub enum PaymentInstrument {
Card(CardPayment),
CardToken(CardToken),
+ RawCardForNTI(RawCardDetails),
Googlepay(WalletPayment),
Applepay(WalletPayment),
}
@@ -85,15 +90,22 @@ pub enum PaymentInstrument {
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPayment {
- #[serde(rename = "type")]
- pub payment_type: PaymentType,
+ #[serde(flatten)]
+ pub raw_card_details: RawCardDetails,
+ pub cvc: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_holder_name: Option<Secret<String>>,
- pub card_number: cards::CardNumber,
- pub expiry_date: ExpiryDate,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address: Option<BillingAddress>,
- pub cvc: Secret<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RawCardDetails {
+ #[serde(rename = "type")]
+ pub payment_type: PaymentType,
+ pub card_number: cards::CardNumber,
+ pub expiry_date: ExpiryDate,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
index 5e9fb030424..b4d6a370401 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
@@ -43,6 +43,8 @@ pub struct AuthorizedResponse {
pub fraud: Option<Fraud>,
/// Mandate's token
pub token: Option<MandateToken>,
+ /// Network transaction ID
+ pub scheme_reference: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -429,9 +431,13 @@ pub struct WorldpayWebhookTransactionId {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventDetails {
- pub transaction_reference: String,
#[serde(rename = "type")]
pub event_type: EventType,
+ pub transaction_reference: String,
+ /// Mandate's token
+ pub token: Option<MandateToken>,
+ /// Network transaction ID
+ pub scheme_reference: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
index ec23b520a20..cd028e81ef1 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
@@ -76,12 +76,14 @@ fn fetch_payment_instrument(
) -> CustomResult<PaymentInstrument, errors::ConnectorError> {
match payment_method {
PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment {
- payment_type: PaymentType::Plain,
- expiry_date: ExpiryDate {
- month: card.get_expiry_month_as_i8()?,
- year: card.get_expiry_year_as_4_digit_i32()?,
+ raw_card_details: RawCardDetails {
+ payment_type: PaymentType::Plain,
+ expiry_date: ExpiryDate {
+ month: card.get_expiry_month_as_i8()?,
+ year: card.get_expiry_year_as_4_digit_i32()?,
+ },
+ card_number: card.card_number,
},
- card_number: card.card_number,
cvc: card.card_cvc,
card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()),
billing_address: if let Some(address) =
@@ -107,6 +109,16 @@ fn fetch_payment_instrument(
None
},
})),
+ PaymentMethodData::CardDetailsForNetworkTransactionId(raw_card_details) => {
+ Ok(PaymentInstrument::RawCardForNTI(RawCardDetails {
+ payment_type: PaymentType::Plain,
+ expiry_date: ExpiryDate {
+ month: raw_card_details.get_expiry_month_as_i8()?,
+ year: raw_card_details.get_expiry_year_as_4_digit_i32()?,
+ },
+ card_number: raw_card_details.card_number,
+ }))
+ }
PaymentMethodData::MandatePayment => mandate_ids
.and_then(|mandate_ids| {
mandate_ids
@@ -185,13 +197,10 @@ fn fetch_payment_instrument(
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_)
- | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("worldpay"),
- )
- .into())
- }
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("worldpay"),
+ )
+ .into()),
}
}
@@ -439,6 +448,7 @@ fn get_token_and_agreement(
payment_method_data: &PaymentMethodData,
setup_future_usage: Option<enums::FutureUsage>,
off_session: Option<bool>,
+ mandate_ids: Option<MandateIds>,
) -> (Option<TokenCreation>, Option<CustomerAgreement>) {
match (payment_method_data, setup_future_usage, off_session) {
// CIT
@@ -448,7 +458,8 @@ fn get_token_and_agreement(
}),
Some(CustomerAgreement {
agreement_type: CustomerAgreementType::Subscription,
- stored_card_usage: StoredCardUsageType::First,
+ stored_card_usage: Some(StoredCardUsageType::First),
+ scheme_reference: None,
}),
),
// MIT
@@ -456,7 +467,26 @@ fn get_token_and_agreement(
None,
Some(CustomerAgreement {
agreement_type: CustomerAgreementType::Subscription,
- stored_card_usage: StoredCardUsageType::Subsequent,
+ stored_card_usage: Some(StoredCardUsageType::Subsequent),
+ scheme_reference: None,
+ }),
+ ),
+ // NTI with raw card data
+ (PaymentMethodData::CardDetailsForNetworkTransactionId(_), _, _) => (
+ None,
+ mandate_ids.and_then(|mandate_ids| {
+ mandate_ids
+ .mandate_reference_id
+ .and_then(|mandate_id| match mandate_id {
+ MandateReferenceId::NetworkMandateId(network_transaction_id) => {
+ Some(CustomerAgreement {
+ agreement_type: CustomerAgreementType::Unscheduled,
+ scheme_reference: Some(network_transaction_id.into()),
+ stored_card_usage: None,
+ })
+ }
+ _ => None,
+ })
}),
),
_ => (None, None),
@@ -487,6 +517,7 @@ impl<T: WorldpayPaymentsRequestData> TryFrom<(&WorldpayRouterData<&T>, &Secret<S
item.router_data.get_payment_method_data(),
item.router_data.get_setup_future_usage(),
item.router_data.get_off_session(),
+ item.router_data.get_mandate_id(),
);
Ok(Self {
@@ -646,7 +677,7 @@ impl<F, T>
),
) -> Result<Self, Self::Error> {
let (router_data, optional_correlation_id) = item;
- let (description, redirection_data, mandate_reference, error) = router_data
+ let (description, redirection_data, mandate_reference, network_txn_id, error) = router_data
.response
.other_fields
.as_ref()
@@ -660,6 +691,7 @@ impl<F, T>
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}),
+ res.scheme_reference.clone(),
None,
),
WorldpayPaymentResponseFields::DDCResponse(res) => (
@@ -681,6 +713,7 @@ impl<F, T>
}),
None,
None,
+ None,
),
WorldpayPaymentResponseFields::ThreeDsChallenged(res) => (
None,
@@ -694,16 +727,18 @@ impl<F, T>
}),
None,
None,
+ None,
),
WorldpayPaymentResponseFields::RefusedResponse(res) => (
None,
None,
None,
+ None,
Some((res.refusal_code.clone(), res.refusal_description.clone())),
),
- WorldpayPaymentResponseFields::FraudHighRisk(_) => (None, None, None, None),
+ WorldpayPaymentResponseFields::FraudHighRisk(_) => (None, None, None, None, None),
})
- .unwrap_or((None, None, None, None));
+ .unwrap_or((None, None, None, None, None));
let worldpay_status = router_data.response.outcome.clone();
let optional_error_message = match worldpay_status {
PaymentOutcome::ThreeDsAuthenticationFailed => {
@@ -725,7 +760,7 @@ impl<F, T>
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
- network_txn_id: None,
+ network_txn_id: network_txn_id.map(|id| id.expose()),
connector_response_reference_id: optional_correlation_id.clone(),
incremental_authorization_allowed: None,
charge_id: None,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 190a4eb2566..671aed36378 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -17,7 +17,7 @@ use common_utils::{
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
address::{Address, AddressDetails, PhoneDetails},
- payment_method_data::{self, Card, PaymentMethodData},
+ payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData},
router_data::{
ApplePayPredecryptData, ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData,
},
@@ -1040,6 +1040,97 @@ impl CardData for Card {
}
}
+impl CardData for CardDetailsForNetworkTransactionId {
+ fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let binding = self.card_exp_year.clone();
+ let year = binding.peek();
+ Ok(Secret::new(
+ year.get(year.len() - 2..)
+ .ok_or(errors::ConnectorError::RequestEncodingFailed)?
+ .to_string(),
+ ))
+ }
+ fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
+ get_card_issuer(self.card_number.peek())
+ }
+ fn get_card_expiry_month_year_2_digit_with_delimiter(
+ &self,
+ delimiter: String,
+ ) -> Result<Secret<String>, errors::ConnectorError> {
+ let year = self.get_card_expiry_year_2_digit()?;
+ Ok(Secret::new(format!(
+ "{}{}{}",
+ self.card_exp_month.peek(),
+ delimiter,
+ year.peek()
+ )))
+ }
+ fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
+ let year = self.get_expiry_year_4_digit();
+ Secret::new(format!(
+ "{}{}{}",
+ year.peek(),
+ delimiter,
+ self.card_exp_month.peek()
+ ))
+ }
+ fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
+ let year = self.get_expiry_year_4_digit();
+ Secret::new(format!(
+ "{}{}{}",
+ self.card_exp_month.peek(),
+ delimiter,
+ year.peek()
+ ))
+ }
+ fn get_expiry_year_4_digit(&self) -> Secret<String> {
+ let mut year = self.card_exp_year.peek().clone();
+ if year.len() == 2 {
+ year = format!("20{}", year);
+ }
+ Secret::new(year)
+ }
+ fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let year = self.get_card_expiry_year_2_digit()?.expose();
+ let month = self.card_exp_month.clone().expose();
+ Ok(Secret::new(format!("{year}{month}")))
+ }
+ fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let year = self.get_card_expiry_year_2_digit()?.expose();
+ let month = self.card_exp_month.clone().expose();
+ Ok(Secret::new(format!("{month}{year}")))
+ }
+ fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
+ self.card_exp_month
+ .peek()
+ .clone()
+ .parse::<i8>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+ fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
+ self.card_exp_year
+ .peek()
+ .clone()
+ .parse::<i32>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+ fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
+ self.get_expiry_year_4_digit()
+ .peek()
+ .clone()
+ .parse::<i32>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+ fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
+ self.card_holder_name
+ .clone()
+ .ok_or_else(missing_field_err("card.card_holder_name"))
+ }
+}
+
#[track_caller]
fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> {
for (k, v) in CARD_REGEX.iter() {
diff --git a/crates/router/locales/en.yml b/crates/router/locales/en.yml
index c85be7ccf46..67eec844fb1 100644
--- a/crates/router/locales/en.yml
+++ b/crates/router/locales/en.yml
@@ -7,7 +7,7 @@ payout_link:
status:
title: "Payout Status"
info:
- ref_id: "Ref Id"
+ ref_id: "Reference Id"
error_code: "Error Code"
error_message: "Error Message"
message:
diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs
index 1d2be85ba17..d957109bcef 100644
--- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs
+++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs
@@ -67,6 +67,7 @@ impl Default for Mandates {
enums::Connector::Authorizedotnet,
enums::Connector::Globalpay,
enums::Connector::Worldpay,
+ enums::Connector::Fiuu,
enums::Connector::Multisafepay,
enums::Connector::Nexinets,
enums::Connector::Noon,
@@ -88,6 +89,7 @@ impl Default for Mandates {
enums::Connector::Authorizedotnet,
enums::Connector::Globalpay,
enums::Connector::Worldpay,
+ enums::Connector::Fiuu,
enums::Connector::Multisafepay,
enums::Connector::Nexinets,
enums::Connector::Noon,
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js b/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js
index 996356117ab..a707643248e 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js
@@ -382,6 +382,21 @@ export const connectorDetails = {
},
},
},
+ PaymentIntentOffSession: {
+ Request: {
+ amount: 6500,
+ authentication_type: "no_three_ds",
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "off_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ },
+ },
+ },
PaymentMethodIdMandateNo3DSAutoCapture: {
Request: {
payment_method: "card",
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Novalnet.js b/cypress-tests/cypress/e2e/PaymentUtils/Novalnet.js
index 049997c541c..1025b474114 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Novalnet.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Novalnet.js
@@ -7,22 +7,24 @@ const successfulThreeDSTestCardDetails = {
};
const successfulNo3DSCardDetails = {
- card_number: "4242424242424242",
- card_exp_month: "01",
- card_exp_year: "50",
+ card_number: "4200000000000000",
+ card_exp_month: "03",
+ card_exp_year: "30",
card_holder_name: "joseph Doe",
card_cvc: "123",
};
-const singleUseMandateData = {
- 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",
- },
+const customerAcceptance = {
+ acceptance_type: "offline",
+ accepted_at: "1963-05-03T04:07:52.723Z",
+ online: {
+ ip_address: "127.0.0.1",
+ user_agent: "amet irure esse",
},
+};
+
+const singleUseMandateData = {
+ customer_acceptance: customerAcceptance,
mandate_type: {
single_use: {
amount: 8000,
@@ -260,6 +262,41 @@ export const connectorDetails = {
},
},
},
+ MITAutoCapture: {
+ Request: {},
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+ MITManualCapture: {
+ Request: {},
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+ SaveCardUseNo3DSAutoCaptureOffSession: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ setup_future_usage: "off_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
ZeroAuthPaymentIntent: {
Request: {
amount: 0,
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js b/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js
index a58bbb22f81..a811cac786e 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/WorldPay.js
@@ -56,14 +56,14 @@ const paymentMethodDataNoThreeDsResponse = {
card_extended_bin: null,
card_exp_month: "10",
card_exp_year: "30",
- card_holder_name: null,
+ card_holder_name: "morino",
payment_checks: null,
authentication_data: null,
},
billing: null,
};
-const payment_method_data_3ds = {
+const paymentMethodDataThreeDsResponse = {
card: {
last4: "1091",
card_type: "CREDIT",
@@ -74,7 +74,7 @@ const payment_method_data_3ds = {
card_extended_bin: null,
card_exp_month: "10",
card_exp_year: "30",
- card_holder_name: null,
+ card_holder_name: "morino",
payment_checks: null,
authentication_data: null,
},
@@ -328,7 +328,7 @@ export const connectorDetails = {
body: {
status: "requires_customer_action",
setup_future_usage: "on_session",
- payment_method_data: payment_method_data_3ds,
+ payment_method_data: paymentMethodDataThreeDsResponse,
},
},
},
@@ -349,7 +349,7 @@ export const connectorDetails = {
body: {
status: "requires_customer_action",
setup_future_usage: "on_session",
- payment_method_data: payment_method_data_3ds,
+ payment_method_data: paymentMethodDataThreeDsResponse,
},
},
},
@@ -512,6 +512,73 @@ export const connectorDetails = {
},
},
},
+ PaymentIntentOffSession: {
+ Request: {
+ amount: 6500,
+ authentication_type: "no_three_ds",
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "off_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ },
+ },
+ },
+ MITAutoCapture: {
+ Request: {},
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ },
+ },
+ },
+ MITManualCapture: {
+ Request: {},
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_capture",
+ },
+ },
+ },
+ PaymentIntentWithShippingCost: {
+ Request: {
+ currency: "USD",
+ shipping_cost: 50,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ shipping_cost: 50,
+ amount: 6500,
+ },
+ },
+ },
+ PaymentConfirmWithShippingCost: {
+ Request: {
+ payment_method: "card",
+ payment_method_data: {
+ card: successfulNoThreeDsCardDetailsRequest,
+ },
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ shipping_cost: 50,
+ amount_received: 6550,
+ amount: 6500,
+ net_amount: 6550,
+ },
+ },
+ },
ZeroAuthMandate: {
Request: {
payment_method: "card",
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index b26b5b2e438..e90eb16ab61 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -370,7 +370,7 @@ card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
[network_transaction_id_supported_connectors]
-connector_list = "stripe,adyen,cybersource"
+connector_list = "adyen,cybersource,novalnet,stripe,worldpay"
[analytics]
source = "sqlx"
|
feat
|
fiuu,novalnet,worldpay - extend NTI flows (#6946)
|
7f5695df938cebddc38f2eba0d814eeb8854daa9
|
2023-09-05 20:01:44
|
github-actions
|
chore(version): v1.34.1
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 03b52455a14..cf32f24e1ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,25 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.34.1 (2023-09-05)
+
+### Bug Fixes
+
+- Add accounts_cache for release ([#2087](https://github.com/juspay/hyperswitch/pull/2087)) ([`e5d3180`](https://github.com/juspay/hyperswitch/commit/e5d31801ec671191ab0365cf9650fb467f252102))
+
+### Refactors
+
+- **router:** New separate routes for applepay merchant verification ([#2083](https://github.com/juspay/hyperswitch/pull/2083)) ([`dc908f6`](https://github.com/juspay/hyperswitch/commit/dc908f6902d3260b08ebf0019b2466553871de0e))
+
+### Testing
+
+- **postman:** Update postman collection files ([#2070](https://github.com/juspay/hyperswitch/pull/2070)) ([`cfa6ae8`](https://github.com/juspay/hyperswitch/commit/cfa6ae895d72cb6c0e79d1ee6616183f35121be1))
+
+**Full Changelog:** [`v1.34.0...v1.34.1`](https://github.com/juspay/hyperswitch/compare/v1.34.0...v1.34.1)
+
+- - -
+
+
## 1.34.0 (2023-09-04)
### Features
|
chore
|
v1.34.1
|
cc473590cbd890c41c1e5f5cb034f4329243e579
|
2022-11-28 10:19:57
|
Sanchith Hegde
|
feat(router): include git commit hash and timestamp in `--version` output (#29)
| false
|
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 5211b034eb5..982c1130207 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -7,6 +7,7 @@ default-run = "router"
rust-version = "1.63"
readme = "README.md"
license = "Apache-2.0"
+build = "src/build.rs"
[features]
default = []
@@ -73,6 +74,9 @@ time = { version = "0.3.14", features = ["macros"] }
tokio = "1.21.2"
toml = "0.5.9"
+[build-dependencies]
+router_env = { version = "0.1.0", path = "../router_env", default-features = false, features = ["vergen"] }
+
[[bin]]
name = "router"
path = "src/bin/router.rs"
diff --git a/crates/router/src/build.rs b/crates/router/src/build.rs
new file mode 100644
index 00000000000..4b07385af68
--- /dev/null
+++ b/crates/router/src/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ router_env::vergen::generate_cargo_instructions();
+}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index d4dfbfb360c..6d1dd47e98d 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -11,6 +11,7 @@ use crate::{
};
#[derive(StructOpt, Default)]
+#[structopt(version = router_env::version!())]
pub struct CmdLineConf {
/// Config file.
/// Application will look for "config/config.toml" if this option isn't specified.
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 53f994356ff..e97dc09d198 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -27,12 +27,13 @@ tracing-appender = "0.2.2"
tracing-core = "0.1.29"
tracing-opentelemetry = { version = "0.17" }
tracing-subscriber = { version = "0.3.15", default-features = true, features = ["json", "env-filter", "registry"] }
+vergen = { version = "7.4.2", optional = true }
[dev-dependencies]
tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
-vergen = { version = "7.4.2" }
+vergen = "7.4.2"
[features]
default = ["actix_web"]
diff --git a/crates/router_env/src/build.rs b/crates/router_env/src/build.rs
index 28436458f30..aca12d76a1d 100644
--- a/crates/router_env/src/build.rs
+++ b/crates/router_env/src/build.rs
@@ -1,50 +1,5 @@
-use vergen::{vergen, Config, ShaKind};
+include!("vergen.rs");
fn main() {
- let mut config = Config::default();
-
- let build = config.build_mut();
- *build.enabled_mut() = false;
- *build.skip_if_error_mut() = true;
-
- let cargo = config.cargo_mut();
- *cargo.enabled_mut() = true;
- *cargo.features_mut() = false;
- *cargo.profile_mut() = true;
- *cargo.target_triple_mut() = true;
-
- let git = config.git_mut();
- *git.enabled_mut() = true;
- *git.commit_author_mut() = false;
- *git.commit_count_mut() = false;
- *git.commit_message_mut() = false;
- *git.commit_timestamp_mut() = true;
- *git.semver_mut() = false;
- *git.skip_if_error_mut() = true;
- *git.sha_kind_mut() = ShaKind::Both;
- *git.skip_if_error_mut() = true;
-
- let rustc = config.rustc_mut();
- *rustc.enabled_mut() = true;
- *rustc.channel_mut() = false;
- *rustc.commit_date_mut() = false;
- *rustc.host_triple_mut() = false;
- *rustc.llvm_version_mut() = false;
- *rustc.semver_mut() = true;
- *rustc.sha_mut() = true; // required for sever been available
- *rustc.skip_if_error_mut() = true;
-
- let sysinfo = config.sysinfo_mut();
- *sysinfo.enabled_mut() = false;
- *sysinfo.os_version_mut() = false;
- *sysinfo.user_mut() = false;
- *sysinfo.memory_mut() = false;
- *sysinfo.cpu_vendor_mut() = false;
- *sysinfo.cpu_core_count_mut() = false;
- *sysinfo.cpu_name_mut() = false;
- *sysinfo.cpu_brand_mut() = false;
- *sysinfo.cpu_frequency_mut() = false;
- *sysinfo.skip_if_error_mut() = true;
-
- vergen(config).expect("Problem determining current platform characteristics");
+ generate_cargo_instructions();
}
diff --git a/crates/router_env/src/env.rs b/crates/router_env/src/env.rs
index 229186f6dc5..518a1cac0cf 100644
--- a/crates/router_env/src/env.rs
+++ b/crates/router_env/src/env.rs
@@ -73,23 +73,25 @@ pub fn workspace_path() -> PathBuf {
}
}
-/// Version defined in the crate file.
+/// Version of the crate containing the following information:
///
-/// Example: `0.1.0`.
+/// - Semantic Version from the latest git tag. If tags are not present in the repository, crate
+/// version from the crate manifest is used instead.
+/// - Short hash of the latest git commit.
+/// - Timestamp of the latest git commit.
///
-
+/// Example: `0.1.0-abcd012-2038-01-19T03:14:08Z`.
#[macro_export]
macro_rules! version {
- (
- ) => {{
+ () => {
concat!(
- env!("CARGO_PKG_VERSION"),
+ env!("VERGEN_GIT_SEMVER"),
"-",
env!("VERGEN_GIT_SHA_SHORT"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
)
- }};
+ };
}
///
@@ -107,8 +109,7 @@ macro_rules! version {
#[macro_export]
macro_rules! build {
- (
- ) => {{
+ () => {
concat!(
env!("CARGO_PKG_VERSION"),
"-",
@@ -122,7 +123,7 @@ macro_rules! build {
"-",
env!("VERGEN_CARGO_TARGET_TRIPLE"),
)
- }};
+ };
}
///
@@ -133,10 +134,9 @@ macro_rules! build {
#[macro_export]
macro_rules! commit {
- (
- ) => {{
+ () => {
env!("VERGEN_GIT_SHA")
- }};
+ };
}
// ///
@@ -166,10 +166,9 @@ macro_rules! commit {
#[macro_export]
macro_rules! service_name {
- (
- ) => {{
+ () => {
env!("CARGO_CRATE_NAME")
- }};
+ };
}
///
@@ -180,8 +179,7 @@ macro_rules! service_name {
#[macro_export]
macro_rules! profile {
- (
- ) => {
+ () => {
env!("VERGEN_CARGO_PROFILE")
};
}
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index 3ecefb7a362..93eab6e2dcf 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -19,10 +19,12 @@
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
pub mod env;
-#[doc(inline)]
-pub use env::*;
-
pub mod logger;
+/// `cargo` build instructions generation for obtaining information about the application
+/// environment.
+#[cfg(feature = "vergen")]
+pub mod vergen;
+
// pub use literally;
#[doc(inline)]
pub use logger::*;
@@ -31,3 +33,6 @@ pub use tracing;
#[cfg(feature = "actix_web")]
pub use tracing_actix_web;
pub use tracing_appender;
+
+#[doc(inline)]
+pub use self::env::*;
diff --git a/crates/router_env/src/vergen.rs b/crates/router_env/src/vergen.rs
new file mode 100644
index 00000000000..22e16605a2b
--- /dev/null
+++ b/crates/router_env/src/vergen.rs
@@ -0,0 +1,60 @@
+/// Configures the [`vergen`][::vergen] crate to generate the `cargo` build instructions.
+///
+/// This function should be typically called within build scripts to generate `cargo` build
+/// instructions for the corresponding crate.
+///
+/// # Panics
+///
+/// Panics if `vergen` fails to generate `cargo` build instructions.
+#[allow(clippy::expect_used)]
+pub fn generate_cargo_instructions() {
+ use vergen::{vergen, Config, ShaKind};
+
+ let mut config = Config::default();
+
+ let build = config.build_mut();
+ *build.enabled_mut() = false;
+ *build.skip_if_error_mut() = true;
+
+ let cargo = config.cargo_mut();
+ *cargo.enabled_mut() = true;
+ *cargo.features_mut() = false;
+ *cargo.profile_mut() = true;
+ *cargo.target_triple_mut() = true;
+
+ let git = config.git_mut();
+ *git.enabled_mut() = true;
+ *git.commit_author_mut() = false;
+ *git.commit_count_mut() = false;
+ *git.commit_message_mut() = false;
+ *git.commit_timestamp_mut() = true;
+ *git.semver_mut() = true;
+ *git.semver_dirty_mut() = Some("-dirty");
+ *git.skip_if_error_mut() = true;
+ *git.sha_kind_mut() = ShaKind::Both;
+ *git.skip_if_error_mut() = true;
+
+ let rustc = config.rustc_mut();
+ *rustc.enabled_mut() = true;
+ *rustc.channel_mut() = false;
+ *rustc.commit_date_mut() = false;
+ *rustc.host_triple_mut() = false;
+ *rustc.llvm_version_mut() = false;
+ *rustc.semver_mut() = true;
+ *rustc.sha_mut() = true; // required for semver to be available
+ *rustc.skip_if_error_mut() = true;
+
+ let sysinfo = config.sysinfo_mut();
+ *sysinfo.enabled_mut() = false;
+ *sysinfo.os_version_mut() = false;
+ *sysinfo.user_mut() = false;
+ *sysinfo.memory_mut() = false;
+ *sysinfo.cpu_vendor_mut() = false;
+ *sysinfo.cpu_core_count_mut() = false;
+ *sysinfo.cpu_name_mut() = false;
+ *sysinfo.cpu_brand_mut() = false;
+ *sysinfo.cpu_frequency_mut() = false;
+ *sysinfo.skip_if_error_mut() = true;
+
+ vergen(config).expect("Failed to generate `cargo` build instructions");
+}
|
feat
|
include git commit hash and timestamp in `--version` output (#29)
|
b4eb6016a4e696acf155732592a6571363c24e64
|
2024-08-01 19:10:36
|
Mani Chandra
|
feat(auth): Add `profile_id` in `AuthenticationData` (#5492)
| false
|
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 40741c76198..457a71dff8b 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -138,7 +138,9 @@ pub async fn signup(
.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 token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
let response =
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
@@ -894,6 +896,7 @@ async fn handle_new_user_invitation(
merchant_id: user_from_token.merchant_id.clone(),
org_id: user_from_token.org_id.clone(),
role_id: request.role_id.clone(),
+ profile_id: None,
};
let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
@@ -1036,8 +1039,12 @@ pub async fn accept_invite_from_email(
.change_context(UserErrors::InternalServerError)?
.into();
- let token =
- utils::user::generate_jwt_auth_token(&state, &user_from_db, &update_status_result).await?;
+ let token = utils::user::generate_jwt_auth_token_without_profile(
+ &state,
+ &user_from_db,
+ &update_status_result,
+ )
+ .await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result)
.await;
@@ -1263,6 +1270,7 @@ pub async fn switch_merchant_id(
request.merchant_id.clone(),
org_id.clone(),
user_from_token.role_id.clone(),
+ None,
)
.await?;
@@ -1295,7 +1303,8 @@ pub async fn switch_merchant_id(
.ok_or(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User doesn't have access to switch")?;
- let token = utils::user::generate_jwt_auth_token(&state, &user, user_role).await?;
+ let token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user, user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, user_role).await;
(token, user_role.role_id.clone())
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index a728836857c..b5c7f6db016 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -169,7 +169,9 @@ pub async fn transfer_org_ownership(
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 token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
let response =
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
@@ -246,7 +248,9 @@ pub async fn merchant_select(
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 token =
+ utils::user::generate_jwt_auth_token_without_profile(&state, &user_from_db, &user_role)
+ .await?;
let response = utils::user::get_dashboard_entry_response(
&state,
user_from_db,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index d707ec17c3a..2e43d469815 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -273,6 +273,7 @@ impl MerchantAccountInterface for Store {
.change_context(errors::StorageError::DecryptionError)?,
key_store,
+ profile_id: None,
})
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index df59083537f..0b2066fdb13 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -54,6 +54,14 @@ mod detached;
pub struct AuthenticationData {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
+ pub profile_id: Option<String>,
+}
+
+#[derive(Clone)]
+pub struct AuthenticationDataWithMultipleProfiles {
+ pub merchant_account: domain::MerchantAccount,
+ pub key_store: domain::MerchantKeyStore,
+ pub profile_id_list: Option<Vec<String>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
@@ -178,6 +186,7 @@ pub struct AuthToken {
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
+ pub profile_id: Option<String>,
}
#[cfg(feature = "olap")]
@@ -188,6 +197,7 @@ impl AuthToken {
role_id: String,
settings: &Settings,
org_id: id_type::OrganizationId,
+ profile_id: Option<String>,
) -> 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();
@@ -197,6 +207,7 @@ impl AuthToken {
role_id,
exp,
org_id,
+ profile_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
@@ -208,6 +219,7 @@ pub struct UserFromToken {
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
+ pub profile_id: Option<String>,
}
pub struct UserIdFromAuth {
@@ -376,6 +388,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: None,
};
Ok((
auth.clone(),
@@ -512,6 +525,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: None,
};
Ok(auth)
@@ -735,6 +749,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: None,
};
Ok((
auth.clone(),
@@ -852,6 +867,61 @@ where
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
+ profile_id: payload.profile_id,
+ },
+ AuthenticationType::MerchantJwt {
+ merchant_id: payload.merchant_id,
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+}
+
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationDataWithMultipleProfiles, A> for JWTAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationDataWithMultipleProfiles, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
+ let key_manager_state = &(&state.session_state()).into();
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &payload.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &payload.merchant_id,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
+
+ Ok((
+ AuthenticationDataWithMultipleProfiles {
+ key_store,
+ merchant_account: merchant,
+ profile_id_list: None,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
@@ -1020,6 +1090,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: payload.profile_id,
};
Ok((
auth.clone(),
@@ -1075,6 +1146,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: payload.profile_id,
};
Ok((
(auth.clone(), payload.user_id.clone()),
@@ -1110,6 +1182,7 @@ where
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
+ profile_id: payload.profile_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
@@ -1175,6 +1248,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
+ profile_id: payload.profile_id,
};
Ok((
auth.clone(),
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 1a2ac3fa054..41fbc96f6d2 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1144,8 +1144,12 @@ impl SignInWithSingleRoleStrategy {
self,
state: &SessionState,
) -> UserResult<user_api::SignInResponse> {
- let token =
- utils::user::generate_jwt_auth_token(state, &self.user, &self.user_role).await?;
+ let token = utils::user::generate_jwt_auth_token_without_profile(
+ state,
+ &self.user,
+ &self.user_role,
+ )
+ .await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await;
let dashboard_entry_response =
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index cffdd05448a..92f1d4ba5ba 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -101,7 +101,7 @@ impl JWTFlow {
Ok(true)
}
- pub async fn generate_jwt(
+ pub async fn generate_jwt_without_profile(
self,
state: &SessionState,
next_flow: &NextFlow,
@@ -119,6 +119,7 @@ impl JWTFlow {
.org_id
.clone()
.ok_or(report!(UserErrors::InternalServerError))?,
+ None,
)
.await
.map(|token| token.into())
@@ -293,7 +294,9 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role)
.await;
- jwt_flow.generate_jwt(state, self, &user_role).await
+ jwt_flow
+ .generate_jwt_without_profile(state, self, &user_role)
+ .await
}
}
}
@@ -313,7 +316,9 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role)
.await;
- jwt_flow.generate_jwt(state, self, user_role).await
+ jwt_flow
+ .generate_jwt_without_profile(state, self, user_role)
+ .await
}
}
}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 72d2b83c6b4..2dad55c4b89 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -81,7 +81,7 @@ impl UserFromToken {
}
}
-pub async fn generate_jwt_auth_token(
+pub async fn generate_jwt_auth_token_without_profile(
state: &SessionState,
user: &UserFromStorage,
user_role: &UserRole,
@@ -102,6 +102,7 @@ pub async fn generate_jwt_auth_token(
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("org_id not found for user_role")?
.clone(),
+ None,
)
.await?;
Ok(Secret::new(token))
@@ -113,6 +114,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
+ profile_id: Option<String>,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
@@ -120,6 +122,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
role_id,
&state.conf,
org_id,
+ profile_id,
)
.await?;
Ok(Secret::new(token))
|
feat
|
Add `profile_id` in `AuthenticationData` (#5492)
|
7348d76cad8f52548f84c6a606fb177e7ca3620e
|
2022-12-28 15:24:01
|
Nishant Joshi
|
fix: use non force sync workflow when payment in terminal state (#254)
| false
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index b0e8b6c1e13..4aaddf83fa7 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -994,13 +994,16 @@ pub(crate) fn validate_amount_to_capture(
)
}
-pub fn can_call_connector(status: storage_enums::IntentStatus) -> bool {
- matches!(
+pub fn can_call_connector(status: &storage_enums::AttemptStatus) -> bool {
+ !matches!(
status,
- storage_enums::IntentStatus::Failed
- | storage_enums::IntentStatus::Processing
- | storage_enums::IntentStatus::Succeeded
- | storage_enums::IntentStatus::RequiresCustomerAction
+ storage_enums::AttemptStatus::Charged
+ | storage_enums::AttemptStatus::AutoRefunded
+ | storage_enums::AttemptStatus::Voided
+ | storage_enums::AttemptStatus::CodInitiated
+ | storage_enums::AttemptStatus::Authorized
+ | storage_enums::AttemptStatus::Started
+ | storage_enums::AttemptStatus::Failure
)
}
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 4cf76066045..105f28506db 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -9,7 +9,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
- errors::{self, ApiErrorResponse, CustomResult, RouterResult, StorageErrorExt},
+ errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
@@ -19,7 +19,7 @@ use crate::{
storage::{self, enums},
transformers::ForeignInto,
},
- utils::{self, OptionExt},
+ utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
@@ -109,7 +109,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
&'a self,
state: &'a AppState,
payment_attempt: &storage::PaymentAttempt,
- ) -> CustomResult<(), ApiErrorResponse> {
+ ) -> CustomResult<(), errors::ApiErrorResponse> {
helpers::add_domain_task_to_pt(self, state, payment_attempt).await
}
@@ -118,7 +118,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
merchant_account: &storage::MerchantAccount,
state: &AppState,
request_connector: Option<api_enums::Connector>,
- ) -> CustomResult<api::ConnectorCallType, ApiErrorResponse> {
+ ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
@@ -249,18 +249,6 @@ async fn get_tracker_for_sync<
let billing_address =
helpers::get_address_by_id(db, payment_intent.billing_address_id.clone()).await?;
- utils::when(
- request.force_sync && !helpers::can_call_connector(payment_intent.status),
- || {
- Err(ApiErrorResponse::InvalidRequestData {
- message: format!(
- "cannot perform force_sync as status: {}",
- payment_intent.status
- ),
- })
- },
- )?;
-
let refunds = db
.find_refund_by_payment_id_merchant_id(&payment_id_str, merchant_id, storage_scheme)
.await
@@ -271,7 +259,6 @@ async fn get_tracker_for_sync<
PaymentData {
flow: PhantomData,
payment_intent,
- payment_attempt,
connector_response,
currency,
amount,
@@ -285,7 +272,10 @@ async fn get_tracker_for_sync<
},
confirm: Some(request.force_sync),
payment_method_data: None,
- force_sync: Some(request.force_sync),
+ force_sync: Some(
+ request.force_sync && helpers::can_call_connector(&payment_attempt.status),
+ ),
+ payment_attempt,
refunds,
sessions_token: vec![],
card_cvc: None,
|
fix
|
use non force sync workflow when payment in terminal state (#254)
|
d850f17b87e4eedc66836925136ffbd513d09124
|
2025-01-10 13:08:36
|
Shankar Singh C
|
feat(router): add support for relay refund incoming webhooks (#6974)
| false
|
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index e6f4065eb7a..f99e3a450b2 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -120,6 +120,10 @@ pub enum WebhookResponseTracker {
status: common_enums::MandateStatus,
},
NoEffect,
+ Relay {
+ relay_id: common_utils::id_type::RelayId,
+ status: common_enums::RelayStatus,
+ },
}
impl WebhookResponseTracker {
@@ -132,6 +136,7 @@ impl WebhookResponseTracker {
Self::NoEffect | Self::Mandate { .. } => None,
#[cfg(feature = "payouts")]
Self::Payout { .. } => None,
+ Self::Relay { .. } => None,
}
}
@@ -144,6 +149,7 @@ impl WebhookResponseTracker {
Self::NoEffect | Self::Mandate { .. } => None,
#[cfg(feature = "payouts")]
Self::Payout { .. } => None,
+ Self::Relay { .. } => None,
}
}
}
diff --git a/crates/common_utils/src/id_type/relay.rs b/crates/common_utils/src/id_type/relay.rs
index 3ad64729fb7..c818671e0e5 100644
--- a/crates/common_utils/src/id_type/relay.rs
+++ b/crates/common_utils/src/id_type/relay.rs
@@ -1,3 +1,5 @@
+use std::str::FromStr;
+
crate::id_type!(
RelayId,
"A type for relay_id that can be used for relay ids"
@@ -11,3 +13,12 @@ crate::impl_queryable_id_type!(RelayId);
crate::impl_to_sql_from_sql_id_type!(RelayId);
crate::impl_debug_id_type!(RelayId);
+
+impl FromStr for RelayId {
+ type Err = error_stack::Report<crate::errors::ValidationError>;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let cow_string = std::borrow::Cow::Owned(s.to_string());
+ Self::try_from(cow_string)
+ }
+}
diff --git a/crates/diesel_models/src/query/relay.rs b/crates/diesel_models/src/query/relay.rs
index 034446fe6b5..217f6fd734d 100644
--- a/crates/diesel_models/src/query/relay.rs
+++ b/crates/diesel_models/src/query/relay.rs
@@ -1,4 +1,4 @@
-use diesel::{associations::HasTable, ExpressionMethods};
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
@@ -46,4 +46,18 @@ impl Relay {
)
.await
}
+
+ pub async fn find_by_profile_id_connector_reference_id(
+ conn: &PgPooledConn,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_reference_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .and(dsl::connector_reference_id.eq(connector_reference_id.to_owned())),
+ )
+ .await
+ }
}
diff --git a/crates/hyperswitch_domain_models/src/relay.rs b/crates/hyperswitch_domain_models/src/relay.rs
index 959ac8e7f61..8af58265c39 100644
--- a/crates/hyperswitch_domain_models/src/relay.rs
+++ b/crates/hyperswitch_domain_models/src/relay.rs
@@ -81,7 +81,7 @@ impl RelayUpdate {
match response {
Err(error) => Self::ErrorUpdate {
error_code: error.code,
- error_message: error.message,
+ error_message: error.reason.unwrap_or(error.message),
status: common_enums::RelayStatus::Failure,
},
Ok(response) => Self::StatusUpdate {
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 474a0c628e2..4c1a5aeb780 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -22,9 +22,9 @@ use crate::{
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
- metrics, payments,
- payments::tokenization,
- refunds, utils as core_utils,
+ metrics,
+ payments::{self, tokenization},
+ refunds, relay, utils as core_utils,
webhooks::utils::construct_webhook_router_data,
},
db::StorageInterface,
@@ -62,6 +62,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
key_store: domain::MerchantKeyStore,
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
+ is_relay_webhook: bool,
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let (application_response, webhooks_response_tracker, serialized_req) =
@@ -73,6 +74,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
key_store,
connector_name_or_mca_id,
body.clone(),
+ is_relay_webhook,
))
.await?;
@@ -118,6 +120,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
Ok(application_response)
}
+#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: SessionState,
@@ -127,6 +130,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
key_store: domain::MerchantKeyStore,
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
+ is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
@@ -361,120 +365,162 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
id: profile_id.get_string_repr().to_owned(),
})?;
- let result_response = match flow_type {
- api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
+ // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow
+ let result_response = if is_relay_webhook {
+ let relay_webhook_response = Box::pin(relay_incoming_webhook_flow(
state.clone(),
- req_state,
merchant_account,
business_profile,
key_store,
webhook_details,
- source_verified,
- &connector,
- &request_details,
event_type,
- ))
- .await
- .attach_printable("Incoming webhook flow for payments failed"),
-
- api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(
- state.clone(),
- merchant_account,
- business_profile,
- key_store,
- webhook_details,
- connector_name.as_str(),
source_verified,
- event_type,
))
.await
- .attach_printable("Incoming webhook flow for refunds failed"),
+ .attach_printable("Incoming webhook flow for relay failed");
- api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(
- state.clone(),
- merchant_account,
- business_profile,
- key_store,
- webhook_details,
- source_verified,
- &connector,
- &request_details,
- event_type,
- ))
- .await
- .attach_printable("Incoming webhook flow for disputes failed"),
+ // Using early return ensures unsupported webhooks are acknowledged to the connector
+ if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response
+ .as_ref()
+ .err()
+ .map(|a| a.current_context())
+ {
+ logger::error!(
+ webhook_payload =? request_details.body,
+ "Failed while identifying the event type",
+ );
- api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(
- state.clone(),
- req_state,
- merchant_account,
- business_profile,
- key_store,
- webhook_details,
- source_verified,
- ))
- .await
- .attach_printable("Incoming bank-transfer webhook flow failed"),
+ let response = connector
+ .get_webhook_api_response(&request_details, None)
+ .switch()
+ .attach_printable(
+ "Failed while early return in case of not supported event type in relay webhooks",
+ )?;
+
+ return Ok((
+ response,
+ WebhookResponseTracker::NoEffect,
+ serde_json::Value::Null,
+ ));
+ };
- api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),
+ relay_webhook_response
+ } else {
+ match flow_type {
+ api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
+ state.clone(),
+ req_state,
+ merchant_account,
+ business_profile,
+ key_store,
+ webhook_details,
+ source_verified,
+ &connector,
+ &request_details,
+ event_type,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for payments failed"),
- api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(
- state.clone(),
- merchant_account,
- business_profile,
- key_store,
- webhook_details,
- source_verified,
- event_type,
- ))
- .await
- .attach_printable("Incoming webhook flow for mandates failed"),
+ api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(
+ state.clone(),
+ merchant_account,
+ business_profile,
+ key_store,
+ webhook_details,
+ connector_name.as_str(),
+ source_verified,
+ event_type,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for refunds failed"),
- api::WebhookFlow::ExternalAuthentication => {
- Box::pin(external_authentication_incoming_webhook_flow(
+ api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(
+ state.clone(),
+ merchant_account,
+ business_profile,
+ key_store,
+ webhook_details,
+ source_verified,
+ &connector,
+ &request_details,
+ event_type,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for disputes failed"),
+
+ api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(
+ state.clone(),
+ req_state,
+ merchant_account,
+ business_profile,
+ key_store,
+ webhook_details,
+ source_verified,
+ ))
+ .await
+ .attach_printable("Incoming bank-transfer webhook flow failed"),
+
+ api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),
+
+ api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(
+ state.clone(),
+ merchant_account,
+ business_profile,
+ key_store,
+ webhook_details,
+ source_verified,
+ event_type,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for mandates failed"),
+
+ api::WebhookFlow::ExternalAuthentication => {
+ Box::pin(external_authentication_incoming_webhook_flow(
+ state.clone(),
+ req_state,
+ merchant_account,
+ key_store,
+ source_verified,
+ event_type,
+ &request_details,
+ &connector,
+ object_ref_id,
+ business_profile,
+ merchant_connector_account,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for external authentication failed")
+ }
+ api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(
state.clone(),
req_state,
merchant_account,
key_store,
source_verified,
event_type,
- &request_details,
- &connector,
object_ref_id,
business_profile,
- merchant_connector_account,
))
.await
- .attach_printable("Incoming webhook flow for external authentication failed")
- }
- api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(
- state.clone(),
- req_state,
- merchant_account,
- key_store,
- source_verified,
- event_type,
- object_ref_id,
- business_profile,
- ))
- .await
- .attach_printable("Incoming webhook flow for fraud check failed"),
+ .attach_printable("Incoming webhook flow for fraud check failed"),
- #[cfg(feature = "payouts")]
- api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(
- state.clone(),
- merchant_account,
- business_profile,
- key_store,
- webhook_details,
- event_type,
- source_verified,
- ))
- .await
- .attach_printable("Incoming webhook flow for payouts failed"),
+ #[cfg(feature = "payouts")]
+ api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(
+ state.clone(),
+ merchant_account,
+ business_profile,
+ key_store,
+ webhook_details,
+ event_type,
+ source_verified,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for payouts failed"),
- _ => Err(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unsupported Flow Type received in incoming webhooks"),
+ _ => Err(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unsupported Flow Type received in incoming webhooks"),
+ }
};
match result_response {
@@ -836,6 +882,97 @@ async fn payouts_incoming_webhook_flow(
}
}
+async fn relay_refunds_incoming_webhook_flow(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ business_profile: domain::Profile,
+ merchant_key_store: domain::MerchantKeyStore,
+ webhook_details: api::IncomingWebhookDetails,
+ event_type: webhooks::IncomingWebhookEvent,
+ source_verified: bool,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let key_manager_state = &(&state).into();
+
+ let relay_record = match webhook_details.object_reference_id {
+ webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
+ webhooks::RefundIdType::RefundId(refund_id) => {
+ let relay_id = common_utils::id_type::RelayId::from_str(&refund_id)
+ .change_context(errors::ValidationError::IncorrectValueProvided {
+ field_name: "relay_id",
+ })
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ db.find_relay_by_id(key_manager_state, &merchant_key_store, &relay_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
+ .attach_printable("Failed to fetch the relay record")?
+ }
+ webhooks::RefundIdType::ConnectorRefundId(connector_refund_id) => db
+ .find_relay_by_profile_id_connector_reference_id(
+ key_manager_state,
+ &merchant_key_store,
+ business_profile.get_id(),
+ &connector_refund_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
+ .attach_printable("Failed to fetch the relay record")?,
+ },
+ _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("received a non-refund id when processing relay refund webhooks")?,
+ };
+
+ // if source_verified then update relay status else trigger relay force sync
+ let relay_response = if source_verified {
+ let relay_update = hyperswitch_domain_models::relay::RelayUpdate::StatusUpdate {
+ connector_reference_id: None,
+ status: common_enums::RelayStatus::foreign_try_from(event_type)
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("failed relay refund status mapping from event type")?,
+ };
+ db.update_relay(
+ key_manager_state,
+ &merchant_key_store,
+ relay_record,
+ relay_update,
+ )
+ .await
+ .map(api_models::relay::RelayResponse::from)
+ .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
+ .attach_printable("Failed to update relay")?
+ } else {
+ let relay_retrieve_request = api_models::relay::RelayRetrieveRequest {
+ force_sync: true,
+ id: relay_record.id,
+ };
+ let relay_force_sync_response = Box::pin(relay::relay_retrieve(
+ state,
+ merchant_account,
+ Some(business_profile.get_id().clone()),
+ merchant_key_store,
+ relay_retrieve_request,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to force sync relay")?;
+
+ if let hyperswitch_domain_models::api::ApplicationResponse::Json(response) =
+ relay_force_sync_response
+ {
+ response
+ } else {
+ Err(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unexpected response from force sync relay")?
+ }
+ };
+
+ Ok(WebhookResponseTracker::Relay {
+ relay_id: relay_response.id,
+ status: relay_response.status,
+ })
+}
+
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn refunds_incoming_webhook_flow(
@@ -938,6 +1075,44 @@ async fn refunds_incoming_webhook_flow(
})
}
+async fn relay_incoming_webhook_flow(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ business_profile: domain::Profile,
+ merchant_key_store: domain::MerchantKeyStore,
+ webhook_details: api::IncomingWebhookDetails,
+ event_type: webhooks::IncomingWebhookEvent,
+ source_verified: bool,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ let flow_type: api::WebhookFlow = event_type.into();
+
+ let result_response = match flow_type {
+ webhooks::WebhookFlow::Refund => Box::pin(relay_refunds_incoming_webhook_flow(
+ state,
+ merchant_account,
+ business_profile,
+ merchant_key_store,
+ webhook_details,
+ event_type,
+ source_verified,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for relay refund failed")?,
+ webhooks::WebhookFlow::Payment
+ | webhooks::WebhookFlow::Payout
+ | webhooks::WebhookFlow::Dispute
+ | webhooks::WebhookFlow::Subscription
+ | webhooks::WebhookFlow::ReturnResponse
+ | webhooks::WebhookFlow::BankTransfer
+ | webhooks::WebhookFlow::Mandate
+ | webhooks::WebhookFlow::ExternalAuthentication
+ | webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported {
+ message: "Relay webhook flow types not supported".to_string(),
+ })?,
+ };
+ Ok(result_response)
+}
+
async fn get_payment_attempt_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index 39b7091e73c..5e89f3343b5 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -56,6 +56,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
key_store: domain::MerchantKeyStore,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
body: actix_web::web::Bytes,
+ is_relay_webhook: bool,
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let (application_response, webhooks_response_tracker, serialized_req) =
@@ -68,6 +69,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
key_store,
connector_id,
body.clone(),
+ is_relay_webhook,
))
.await?;
@@ -124,6 +126,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
key_store: domain::MerchantKeyStore,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
body: actix_web::web::Bytes,
+ _is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
diff --git a/crates/router/src/db/relay.rs b/crates/router/src/db/relay.rs
index 46259679c55..2ead84019d8 100644
--- a/crates/router/src/db/relay.rs
+++ b/crates/router/src/db/relay.rs
@@ -35,6 +35,14 @@ pub trait RelayInterface {
merchant_key_store: &domain::MerchantKeyStore,
relay_id: &common_utils::id_type::RelayId,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
+
+ async fn find_relay_by_profile_id_connector_reference_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_reference_id: &str,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -105,6 +113,30 @@ impl RelayInterface for Store {
.await
.change_context(errors::StorageError::DecryptionError)
}
+
+ async fn find_relay_by_profile_id_connector_reference_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_reference_id: &str,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ diesel_models::relay::Relay::find_by_profile_id_connector_reference_id(
+ &conn,
+ profile_id,
+ connector_reference_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
}
#[async_trait::async_trait]
@@ -136,6 +168,16 @@ impl RelayInterface for MockDb {
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
+
+ async fn find_relay_by_profile_id_connector_reference_id(
+ &self,
+ _key_manager_state: &KeyManagerState,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _profile_id: &common_utils::id_type::ProfileId,
+ _connector_reference_id: &str,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
}
#[async_trait::async_trait]
@@ -178,4 +220,21 @@ impl RelayInterface for KafkaStore {
.find_relay_by_id(key_manager_state, merchant_key_store, relay_id)
.await
}
+
+ async fn find_relay_by_profile_id_connector_reference_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+ connector_reference_id: &str,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
+ self.diesel_store
+ .find_relay_by_profile_id_connector_reference_id(
+ key_manager_state,
+ merchant_key_store,
+ profile_id,
+ connector_reference_id,
+ )
+ .await
+ }
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 4fe9318f64b..8c2bca5a82e 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -142,6 +142,7 @@ pub fn mk_app(
.service(routes::Customers::server(state.clone()))
.service(routes::Configs::server(state.clone()))
.service(routes::MerchantConnectorAccount::server(state.clone()))
+ .service(routes::RelayWebhooks::server(state.clone()))
.service(routes::Webhooks::server(state.clone()))
.service(routes::Relay::server(state.clone()));
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 462861d331f..22f5983e4c3 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -69,7 +69,7 @@ pub use self::app::{
ApiKeys, AppState, ApplePayCertificatesMigration, Cache, Cards, Configs, ConnectorOnboarding,
Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, Health, Mandates,
MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll,
- Profile, ProfileNew, Refunds, Relay, SessionState, User, Webhooks,
+ Profile, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, User, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{Blocklist, Organization, Routing, Verify, WebhookEvents};
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index f8b5ef44567..2a9561c06c8 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1515,6 +1515,20 @@ impl Webhooks {
}
}
+pub struct RelayWebhooks;
+
+#[cfg(feature = "oltp")]
+impl RelayWebhooks {
+ pub fn server(state: AppState) -> Scope {
+ use api_models::webhooks as webhook_type;
+ web::scope("/webhooks/relay")
+ .app_data(web::Data::new(state))
+ .service(web::resource("/{merchant_id}/{connector_id}").route(
+ web::post().to(receive_incoming_relay_webhook::<webhook_type::OutgoingWebhook>),
+ ))
+ }
+}
+
#[cfg(all(feature = "oltp", feature = "v2"))]
impl Webhooks {
pub fn server(config: AppState) -> Scope {
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9d7ae1874c1..6550778619a 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -171,6 +171,7 @@ impl From<Flow> for ApiIdentifier {
Flow::FrmFulfillment
| Flow::IncomingWebhookReceive
+ | Flow::IncomingRelayWebhookReceive
| Flow::WebhookEventInitialDeliveryAttemptList
| Flow::WebhookEventDeliveryAttemptList
| Flow::WebhookEventDeliveryRetry => Self::Webhooks,
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index 5427ac34b4e..1b3f28fd256 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -36,6 +36,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
auth.key_store,
&connector_id_or_name,
body.clone(),
+ false,
)
},
&auth::MerchantIdAuth(merchant_id),
@@ -44,6 +45,89 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
.await
}
+#[cfg(feature = "v1")]
+#[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))]
+pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ body: web::Bytes,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::MerchantConnectorAccountId,
+ )>,
+) -> impl Responder {
+ let flow = Flow::IncomingWebhookReceive;
+ let (merchant_id, connector_id) = path.into_inner();
+ let is_relay_webhook = true;
+
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &req,
+ (),
+ |state, auth, _, req_state| {
+ webhooks::incoming_webhooks_wrapper::<W>(
+ &flow,
+ state.to_owned(),
+ req_state,
+ &req,
+ auth.merchant_account,
+ auth.key_store,
+ connector_id.get_string_repr(),
+ body.clone(),
+ is_relay_webhook,
+ )
+ },
+ &auth::MerchantIdAuth(merchant_id),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))]
+pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ body: web::Bytes,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ProfileId,
+ common_utils::id_type::MerchantConnectorAccountId,
+ )>,
+) -> impl Responder {
+ let flow = Flow::IncomingWebhookReceive;
+ let (merchant_id, profile_id, connector_id) = path.into_inner();
+ let is_relay_webhook = true;
+
+ Box::pin(api::server_wrap(
+ flow.clone(),
+ state,
+ &req,
+ (),
+ |state, auth, _, req_state| {
+ webhooks::incoming_webhooks_wrapper::<W>(
+ &flow,
+ state.to_owned(),
+ req_state,
+ &req,
+ auth.merchant_account,
+ auth.profile,
+ auth.key_store,
+ &connector_id,
+ body.clone(),
+ is_relay_webhook,
+ )
+ },
+ &auth::MerchantIdAndProfileIdAuth {
+ merchant_id,
+ profile_id,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))]
#[cfg(feature = "v2")]
pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
@@ -75,6 +159,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
auth.key_store,
&connector_id,
body.clone(),
+ false,
)
},
&auth::MerchantIdAndProfileIdAuth {
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index bbcdfc535df..cb7d3f78f78 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -662,6 +662,22 @@ impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enum
}
}
+impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for api_enums::RelayStatus {
+ type Error = errors::ValidationError;
+
+ fn foreign_try_from(
+ value: api_models::webhooks::IncomingWebhookEvent,
+ ) -> Result<Self, Self::Error> {
+ match value {
+ api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success),
+ api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure),
+ _ => Err(errors::ValidationError::IncorrectValueProvided {
+ field_name: "incoming_webhook_event_type",
+ }),
+ }
+ }
+}
+
#[cfg(feature = "payouts")]
impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus {
type Error = errors::ValidationError;
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 10183f75d5b..935efa3c78b 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -537,6 +537,8 @@ pub enum Flow {
Relay,
/// Relay retrieve flow
RelayRetrieve,
+ /// Incoming Relay Webhook Receive
+ IncomingRelayWebhookReceive,
}
/// Trait for providing generic behaviour to flow metric
diff --git a/migrations/2025-01-07-105739_create_index_for_relay/down.sql b/migrations/2025-01-07-105739_create_index_for_relay/down.sql
new file mode 100644
index 00000000000..8a75d445466
--- /dev/null
+++ b/migrations/2025-01-07-105739_create_index_for_relay/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+DROP INDEX relay_profile_id_connector_reference_id_index;
\ No newline at end of file
diff --git a/migrations/2025-01-07-105739_create_index_for_relay/up.sql b/migrations/2025-01-07-105739_create_index_for_relay/up.sql
new file mode 100644
index 00000000000..5ebe5983c74
--- /dev/null
+++ b/migrations/2025-01-07-105739_create_index_for_relay/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+CREATE UNIQUE INDEX relay_profile_id_connector_reference_id_index ON relay (profile_id, connector_reference_id);
\ No newline at end of file
|
feat
|
add support for relay refund incoming webhooks (#6974)
|
fee0e9dadd2e20c5c75dcee50de0e53f4e5e6deb
|
2023-05-12 00:34:22
|
ThisIsMani
|
feat(connector): add payment, refund urls for dummy connector (#1084)
| false
|
diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs
index 36d34b4d87c..b7928a18c06 100644
--- a/crates/router/src/connector/dummyconnector.rs
+++ b/crates/router/src/connector/dummyconnector.rs
@@ -2,9 +2,11 @@ mod transformers;
use std::fmt::Debug;
+use api_models::payments::PaymentMethodData;
use error_stack::{IntoReport, ResultExt};
use transformers as dummyconnector;
+use super::utils::{PaymentsAuthorizeRequestData, RefundsRequestData};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
@@ -96,9 +98,9 @@ impl ConnectorCommon for DummyConnector {
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response.error.code,
+ message: response.error.message,
+ reason: response.error.reason,
})
}
}
@@ -136,10 +138,22 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let payment_method_data = req.request.payment_method_data.to_owned();
+ let payment_method_type = req.request.get_payment_method_type()?;
+ match payment_method_data {
+ PaymentMethodData::Card(_) => Ok(format!("{}/payment", self.base_url(connectors))),
+ _ => Err(error_stack::report!(errors::ConnectorError::NotSupported {
+ message: format!(
+ "The payment method {} is not supported",
+ payment_method_type
+ ),
+ connector: "dummyconnector",
+ payment_experience: api::enums::PaymentExperience::RedirectToUrl.to_string(),
+ })),
+ }
}
fn get_request_body(
@@ -180,7 +194,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
data: &types::PaymentsAuthorizeRouterData,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: dummyconnector::DummyConnectorPaymentsResponse = res
+ let response: dummyconnector::PaymentsResponse = res
.response
.parse_struct("DummyConnector PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -217,10 +231,23 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ match req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ {
+ Ok(transaction_id) => Ok(format!(
+ "{}/payments/{}",
+ self.base_url(connectors),
+ transaction_id
+ )),
+ Err(_) => Err(error_stack::report!(
+ errors::ConnectorError::MissingConnectorTransactionID
+ )),
+ }
}
fn build_request(
@@ -243,7 +270,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
data: &types::PaymentsSyncRouterData,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: dummyconnector::DummyConnectorPaymentsResponse = res
+ let response: dummyconnector::PaymentsResponse = res
.response
.parse_struct("dummyconnector PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -315,7 +342,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
data: &types::PaymentsCaptureRouterData,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: dummyconnector::DummyConnectorPaymentsResponse = res
+ let response: dummyconnector::PaymentsResponse = res
.response
.parse_struct("DummyConnector PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -357,10 +384,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!(
+ "{}/{}/refund",
+ self.base_url(connectors),
+ req.request.connector_transaction_id
+ ))
}
fn get_request_body(
@@ -435,10 +466,15 @@ 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!(
+ "{}/refunds/{}",
+ self.base_url(connectors),
+ refund_id
+ ))
}
fn build_request(
diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs
index 88404290208..4a8fd08489a 100644
--- a/crates/router/src/connector/dummyconnector/transformers.rs
+++ b/crates/router/src/connector/dummyconnector/transformers.rs
@@ -1,5 +1,6 @@
use masking::Secret;
use serde::{Deserialize, Serialize};
+use storage_models::enums::Currency;
use crate::{
connector::utils::PaymentsAuthorizeRequestData,
@@ -7,14 +8,19 @@ use crate::{
types::{self, api, storage::enums},
};
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct DummyConnectorPaymentsRequest {
amount: i64,
- card: DummyConnectorCard,
+ currency: Currency,
+ payment_method_data: PaymentMethodData,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, serde::Serialize, Eq, PartialEq)]
+pub enum PaymentMethodData {
+ Card(DummyConnectorCard),
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct DummyConnectorCard {
name: Secret<String>,
number: cards::CardNumber,
@@ -39,7 +45,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DummyConnectorPaymentsRequ
};
Ok(Self {
amount: item.request.amount,
- card,
+ currency: item.request.currency,
+ payment_method_data: PaymentMethodData::Card(card),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
@@ -47,7 +54,6 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DummyConnectorPaymentsRequ
}
}
-//TODO: Fill the struct with respective fields
// Auth Struct
pub struct DummyConnectorAuthType {
pub(super) api_key: String,
@@ -85,31 +91,22 @@ impl From<DummyConnectorPaymentStatus> for enums::AttemptStatus {
}
}
-//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct DummyConnectorPaymentsResponse {
+pub struct PaymentsResponse {
status: DummyConnectorPaymentStatus,
id: String,
+ amount: i64,
+ currency: Currency,
+ created: String,
+ payment_method_type: String,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- DummyConnectorPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- DummyConnectorPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: types::ResponseRouterData<F, PaymentsResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
@@ -125,7 +122,6 @@ impl<F, T>
}
}
-//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
@@ -137,7 +133,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for DummyConnectorRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.request.amount,
+ amount: item.request.refund_amount,
})
}
}
@@ -146,6 +142,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for DummyConnectorRefundRequest {
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Succeeded,
Failed,
@@ -164,11 +161,14 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
+ currency: Currency,
+ created: String,
+ payment_amount: i64,
+ refund_amount: i64,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
@@ -205,10 +205,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DummyConnectorErrorResponse {
- pub status_code: u16,
+ pub error: ErrorData,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct ErrorData {
pub code: String,
pub message: String,
pub reason: Option<String>,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index e5221b56e96..50df7926ff3 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -170,6 +170,7 @@ pub trait PaymentsAuthorizeRequestData {
fn is_mandate_payment(&self) -> bool;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_payment_method_type(&self) -> Result<storage_models::enums::PaymentMethodType, Error>;
}
impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
@@ -233,6 +234,11 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
+ fn get_payment_method_type(&self) -> Result<storage_models::enums::PaymentMethodType, Error> {
+ self.payment_method_type
+ .to_owned()
+ .ok_or_else(missing_field_err("payment_method_type"))
+ }
}
pub trait BrowserInformationData {
|
feat
|
add payment, refund urls for dummy connector (#1084)
|
7adc6a05b60fa9143260b2a7f623907647557621
|
2023-10-16 19:21:31
|
Panagiotis Ganelis
|
refactor(connector): [multisafepay] Remove Default Case Handling (#2586)
| false
|
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index a8366fadf81..385c85e0aa6 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -229,11 +229,13 @@ impl TryFrom<utils::CardIssuer> for Gateway {
utils::CardIssuer::Maestro => Ok(Self::Maestro),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
- _ => Err(errors::ConnectorError::NotSupported {
- message: issuer.to_string(),
- connector: "Multisafe pay",
+ utils::CardIssuer::DinersClub | utils::CardIssuer::JCB => {
+ Err(errors::ConnectorError::NotSupported {
+ message: issuer.to_string(),
+ connector: "Multisafe pay",
+ }
+ .into())
}
- .into()),
}
}
}
@@ -247,8 +249,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
api::WalletData::GooglePay(_) => Type::Direct,
api::WalletData::PaypalRedirect(_) => Type::Redirect,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::WalletData::AliPayQr(_)
+ | api::WalletData::AliPayRedirect(_)
+ | api::WalletData::AliPayHkRedirect(_)
+ | api::WalletData::MomoRedirect(_)
+ | api::WalletData::KakaoPayRedirect(_)
+ | api::WalletData::GoPayRedirect(_)
+ | api::WalletData::GcashRedirect(_)
+ | api::WalletData::ApplePay(_)
+ | api::WalletData::ApplePayRedirect(_)
+ | api::WalletData::ApplePayThirdPartySdk(_)
+ | api::WalletData::DanaRedirect {}
+ | api::WalletData::GooglePayRedirect(_)
+ | api::WalletData::GooglePayThirdPartySdk(_)
+ | api::WalletData::MbWayRedirect(_)
+ | api::WalletData::MobilePayRedirect(_)
+ | api::WalletData::PaypalSdk(_)
+ | api::WalletData::SamsungPay(_)
+ | api::WalletData::TwintRedirect {}
+ | api::WalletData::VippsRedirect {}
+ | api::WalletData::TouchNGoRedirect(_)
+ | api::WalletData::WeChatPayRedirect(_)
+ | api::WalletData::WeChatPayQr(_)
+ | api::WalletData::CashappQr(_)
+ | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
api::PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
@@ -262,8 +287,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
api::PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data {
api::WalletData::GooglePay(_) => Gateway::Googlepay,
api::WalletData::PaypalRedirect(_) => Gateway::Paypal,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::WalletData::AliPayQr(_)
+ | api::WalletData::AliPayRedirect(_)
+ | api::WalletData::AliPayHkRedirect(_)
+ | api::WalletData::MomoRedirect(_)
+ | api::WalletData::KakaoPayRedirect(_)
+ | api::WalletData::GoPayRedirect(_)
+ | api::WalletData::GcashRedirect(_)
+ | api::WalletData::ApplePay(_)
+ | api::WalletData::ApplePayRedirect(_)
+ | api::WalletData::ApplePayThirdPartySdk(_)
+ | api::WalletData::DanaRedirect {}
+ | api::WalletData::GooglePayRedirect(_)
+ | api::WalletData::GooglePayThirdPartySdk(_)
+ | api::WalletData::MbWayRedirect(_)
+ | api::WalletData::MobilePayRedirect(_)
+ | api::WalletData::PaypalSdk(_)
+ | api::WalletData::SamsungPay(_)
+ | api::WalletData::TwintRedirect {}
+ | api::WalletData::VippsRedirect {}
+ | api::WalletData::TouchNGoRedirect(_)
+ | api::WalletData::WeChatPayRedirect(_)
+ | api::WalletData::WeChatPayQr(_)
+ | api::WalletData::CashappQr(_)
+ | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
}),
api::PaymentMethodData::PayLater(
@@ -273,8 +321,17 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
},
) => Some(Gateway::Klarna),
api::PaymentMethodData::MandatePayment => None,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
};
let description = item.get_description()?;
@@ -354,8 +411,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
})))
}
api::WalletData::PaypalRedirect(_) => None,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::WalletData::AliPayQr(_)
+ | api::WalletData::AliPayRedirect(_)
+ | api::WalletData::AliPayHkRedirect(_)
+ | api::WalletData::MomoRedirect(_)
+ | api::WalletData::KakaoPayRedirect(_)
+ | api::WalletData::GoPayRedirect(_)
+ | api::WalletData::GcashRedirect(_)
+ | api::WalletData::ApplePay(_)
+ | api::WalletData::ApplePayRedirect(_)
+ | api::WalletData::ApplePayThirdPartySdk(_)
+ | api::WalletData::DanaRedirect {}
+ | api::WalletData::GooglePayRedirect(_)
+ | api::WalletData::GooglePayThirdPartySdk(_)
+ | api::WalletData::MbWayRedirect(_)
+ | api::WalletData::MobilePayRedirect(_)
+ | api::WalletData::PaypalSdk(_)
+ | api::WalletData::SamsungPay(_)
+ | api::WalletData::TwintRedirect {}
+ | api::WalletData::VippsRedirect {}
+ | api::WalletData::TouchNGoRedirect(_)
+ | api::WalletData::WeChatPayRedirect(_)
+ | api::WalletData::WeChatPayQr(_)
+ | api::WalletData::CashappQr(_)
+ | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
api::PaymentMethodData::PayLater(ref paylater) => {
@@ -365,15 +445,36 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
billing_email,
..
} => billing_email.clone(),
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- ))?,
+ api_models::payments::PayLaterData::KlarnaSdk { token: _ }
+ | api_models::payments::PayLaterData::AffirmRedirect {}
+ | api_models::payments::PayLaterData::AfterpayClearpayRedirect {
+ billing_email: _,
+ billing_name: _,
+ }
+ | api_models::payments::PayLaterData::PayBrightRedirect {}
+ | api_models::payments::PayLaterData::WalleyRedirect {}
+ | api_models::payments::PayLaterData::AlmaRedirect {}
+ | api_models::payments::PayLaterData::AtomeRedirect {} => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "multisafepay",
+ ),
+ ))?
+ }
}),
}))
}
api::PaymentMethodData::MandatePayment => None,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
};
|
refactor
|
[multisafepay] Remove Default Case Handling (#2586)
|
46f3f6132aa667c29bea063ad1b04a880ae377d3
|
2024-07-30 05:47:52
|
github-actions
|
chore(version): 2024.07.30.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b72f61905d..cef3256f307 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.07.30.0
+
+### Features
+
+- Add env variable for enable key manager service ([#5442](https://github.com/juspay/hyperswitch/pull/5442)) ([`db26d32`](https://github.com/juspay/hyperswitch/commit/db26d32d8465e20cf3835fbfe6d0a19688078b8c))
+
+### Refactors
+
+- **router:** Remove `connector_account_details` and `connector_webhook_details` in merchant_connector_account list response ([#5457](https://github.com/juspay/hyperswitch/pull/5457)) ([`45a1494`](https://github.com/juspay/hyperswitch/commit/45a149418f1dad0cd27f975dc3dd56c68172b9dd))
+
+**Full Changelog:** [`2024.07.29.0...2024.07.30.0`](https://github.com/juspay/hyperswitch/compare/2024.07.29.0...2024.07.30.0)
+
+- - -
+
## 2024.07.29.0
### Features
|
chore
|
2024.07.30.0
|
303684d1ec723db3ae3b1cf0781609e1616de1cc
|
2024-08-28 13:06:35
|
mrudul4935
|
feat(connector): [NEXIXPAY] Add template code (#5684)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index a8cc36b4dc5..0a88c3896f2 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -222,6 +222,7 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
novalnet.base_url = "https://payport.novalnet.de/v2"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 2ceac401b92..c6cb9ff6c36 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -47,7 +47,6 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
-novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -62,9 +61,11 @@ mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
noon.key_mode = "Test"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index aa214d04007..67256cf34d7 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -51,7 +51,6 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/ipp/payments-gateway/v2"
-novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -66,9 +65,11 @@ mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
nexinets.base_url = "https://api.payengine.de/v1"
+nexixpay.base_url = "https://xpay.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api.noonpayments.com/"
noon.key_mode = "Live"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-live.sagepay.com/"
opennode.base_url = "https://api.opennode.com"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index b6a235a0018..5496c4ae102 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -51,7 +51,6 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2"
-novalnet.base_url = "https://payport.novalnet.de/v2"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -66,9 +65,11 @@ mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
noon.key_mode = "Test"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
diff --git a/config/development.toml b/config/development.toml
index 902c3ed3ad6..401b1487843 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -131,6 +131,7 @@ cards = [
"multisafepay",
"netcetera",
"nexinets",
+ "nexixpay",
"nmi",
"noon",
"novalnet",
@@ -227,6 +228,7 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
novalnet.base_url = "https://payport.novalnet.de/v2"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index e8d564ac66b..136864c9f98 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -151,6 +151,7 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
novalnet.base_url = "https://payport.novalnet.de/v2"
@@ -236,6 +237,7 @@ cards = [
"multisafepay",
"netcetera",
"nexinets",
+ "nexixpay",
"nmi",
"noon",
"novalnet",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 86d6421c3e2..150d69f1e8d 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -47,6 +47,7 @@ pub enum RoutingAlgorithm {
#[strum(serialize_all = "snake_case")]
pub enum Connector {
// Novalnet,
+ // Nexixpay,
// Fiservemea,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
@@ -211,6 +212,7 @@ impl Connector {
Self::Aci
// Add Separate authentication support for connectors
// | Self::Novalnet
+ // | Self::Nexixpay
// | Self::Taxjar
// | Self::Fiservemea
| Self::Adyen
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 617d121c63c..078f490b800 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -160,6 +160,7 @@ pub enum AttemptStatus {
#[strum(serialize_all = "snake_case")]
/// Connectors eligible for payments routing
pub enum RoutableConnectors {
+ // Nexixpay,
Adyenplatform,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "phonypay")]
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index dfaffd02662..331f58a4877 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -3,11 +3,12 @@ pub mod bitpay;
pub mod fiserv;
pub mod fiservemea;
pub mod helcim;
+pub mod nexixpay;
pub mod novalnet;
pub mod stax;
pub mod taxjar;
pub use self::{
bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, fiservemea::Fiservemea, helcim::Helcim,
- novalnet::Novalnet, stax::Stax, taxjar::Taxjar,
+ nexixpay::Nexixpay, novalnet::Novalnet, stax::Stax, taxjar::Taxjar,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
new file mode 100644
index 00000000000..b660445f3ca
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
@@ -0,0 +1,566 @@
+pub mod transformers;
+
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as nexixpay;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Nexixpay {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Nexixpay {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Nexixpay {}
+impl api::PaymentSession for Nexixpay {}
+impl api::ConnectorAccessToken for Nexixpay {}
+impl api::MandateSetup for Nexixpay {}
+impl api::PaymentAuthorize for Nexixpay {}
+impl api::PaymentSync for Nexixpay {}
+impl api::PaymentCapture for Nexixpay {}
+impl api::PaymentVoid for Nexixpay {}
+impl api::Refund for Nexixpay {}
+impl api::RefundExecute for Nexixpay {}
+impl api::RefundSync for Nexixpay {}
+impl api::PaymentToken for Nexixpay {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Nexixpay
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nexixpay
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Nexixpay {
+ fn id(&self) -> &'static str {
+ "nexixpay"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ // TODO! Check connector documentation, on which unit they are processing the currency.
+ // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.nexixpay.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = nexixpay::NexixpayAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: nexixpay::NexixpayErrorResponse = res
+ .response
+ .parse_struct("NexixpayErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Nexixpay {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nexixpay {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nexixpay {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Nexixpay
+{
+}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::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: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = nexixpay::NexixpayRouterData::from((amount, req));
+ let connector_req = nexixpay::NexixpayPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: nexixpay::NexixpayPaymentsResponse = res
+ .response
+ .parse_struct("Nexixpay PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::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: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: nexixpay::NexixpayPaymentsResponse = res
+ .response
+ .parse_struct("nexixpay PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::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: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: nexixpay::NexixpayPaymentsResponse = res
+ .response
+ .parse_struct("Nexixpay PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nexixpay {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::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: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = nexixpay::NexixpayRouterData::from((refund_amount, req));
+ let connector_req = nexixpay::NexixpayRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundsRouterData<Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ let response: nexixpay::RefundResponse = res
+ .response
+ .parse_struct("nexixpay RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nexixpay {
+ fn get_headers(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::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: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ let response: nexixpay::RefundResponse = res
+ .response
+ .parse_struct("nexixpay RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl webhooks::IncomingWebhook for Nexixpay {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
new file mode 100644
index 00000000000..f0bcb1f249e
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
@@ -0,0 +1,228 @@
+use common_enums::enums;
+use common_utils::types::StringMinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
+
+//TODO: Fill the struct with respective fields
+pub struct NexixpayRouterData<T> {
+ pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for NexixpayRouterData<T> {
+ fn from((amount, item): (StringMinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct NexixpayPaymentsRequest {
+ amount: StringMinorUnit,
+ card: NexixpayCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct NexixpayCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = NexixpayCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.clone(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct NexixpayAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for NexixpayAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum NexixpayPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<NexixpayPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: NexixpayPaymentStatus) -> Self {
+ match item {
+ NexixpayPaymentStatus::Succeeded => Self::Charged,
+ NexixpayPaymentStatus::Failed => Self::Failure,
+ NexixpayPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct NexixpayPaymentsResponse {
+ status: NexixpayPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, NexixpayPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, NexixpayPaymentsResponse, T, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct NexixpayRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&NexixpayRouterData<&RefundsRouterData<F>>> for NexixpayRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &NexixpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct NexixpayErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 8da17ae28b0..8283a3e0d62 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -92,6 +92,7 @@ default_imp_for_authorize_session_token!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -118,6 +119,7 @@ default_imp_for_complete_authorize!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -144,6 +146,7 @@ default_imp_for_incremental_authorization!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -170,6 +173,7 @@ default_imp_for_create_customer!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Taxjar
);
@@ -196,6 +200,7 @@ default_imp_for_connector_redirect_response!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -222,6 +227,7 @@ default_imp_for_pre_processing_steps!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -248,6 +254,7 @@ default_imp_for_post_processing_steps!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -274,6 +281,7 @@ default_imp_for_approve!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -300,6 +308,7 @@ default_imp_for_reject!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -326,6 +335,7 @@ default_imp_for_webhook_source_verification!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -353,6 +363,7 @@ default_imp_for_accept_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -379,6 +390,7 @@ default_imp_for_submit_evidence!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -405,6 +417,7 @@ default_imp_for_defend_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -440,6 +453,7 @@ default_imp_for_file_upload!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -468,6 +482,7 @@ default_imp_for_payouts_create!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -496,6 +511,7 @@ default_imp_for_payouts_retrieve!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -524,6 +540,7 @@ default_imp_for_payouts_eligibility!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -552,6 +569,7 @@ default_imp_for_payouts_fulfill!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -580,6 +598,7 @@ default_imp_for_payouts_cancel!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -608,6 +627,7 @@ default_imp_for_payouts_quote!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -636,6 +656,7 @@ default_imp_for_payouts_recipient!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -664,6 +685,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -692,6 +714,7 @@ default_imp_for_frm_sale!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -720,6 +743,7 @@ default_imp_for_frm_checkout!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -748,6 +772,7 @@ default_imp_for_frm_transaction!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -776,6 +801,7 @@ default_imp_for_frm_fulfillment!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -804,6 +830,7 @@ default_imp_for_frm_record_return!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -829,6 +856,7 @@ default_imp_for_revoking_mandates!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 4ebd335ce8f..b837e99c928 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -187,6 +187,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -214,6 +215,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -236,6 +238,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -264,6 +267,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -291,6 +295,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -318,6 +323,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -355,6 +361,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -384,6 +391,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -413,6 +421,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -442,6 +451,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -471,6 +481,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -500,6 +511,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -529,6 +541,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -558,6 +571,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -587,6 +601,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -614,6 +629,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -643,6 +659,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -672,6 +689,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -701,6 +719,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -730,6 +749,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -759,6 +779,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
@@ -785,6 +806,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Fiservemea,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexixpay,
connectors::Stax,
connectors::Taxjar
);
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index bc59bd037d7..f373b1c86af 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -49,6 +49,7 @@ pub struct Connectors {
pub multisafepay: ConnectorParams,
pub netcetera: ConnectorParams,
pub nexinets: ConnectorParams,
+ pub nexixpay: ConnectorParams,
pub nmi: ConnectorParams,
pub noon: ConnectorParamsWithModeType,
pub novalnet: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 5da8f3a8578..667d53ddf6f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -69,8 +69,8 @@ pub mod zsl;
pub use hyperswitch_connectors::connectors::{
bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, fiservemea,
- fiservemea::Fiservemea, helcim, helcim::Helcim, novalnet, novalnet::Novalnet, stax, stax::Stax,
- taxjar, taxjar::Taxjar,
+ fiservemea::Fiservemea, helcim, helcim::Helcim, nexixpay, nexixpay::Nexixpay, novalnet,
+ novalnet::Novalnet, stax, stax::Stax, taxjar, taxjar::Taxjar,
};
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index bed63c10a8a..27fa4b48176 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -1249,6 +1249,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -2095,6 +2096,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -2720,6 +2722,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index aea8748ac67..6cbc320df91 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -554,6 +554,7 @@ default_imp_for_connector_request_id!(
connector::Mollie,
connector::Multisafepay,
connector::Netcetera,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -1209,6 +1210,7 @@ default_imp_for_payouts!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -2229,6 +2231,7 @@ default_imp_for_fraud_check!(
connector::Multisafepay,
connector::Netcetera,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
@@ -3044,6 +3047,7 @@ default_imp_for_connector_authentication!(
connector::Mollie,
connector::Multisafepay,
connector::Nexinets,
+ connector::Nexixpay,
connector::Nmi,
connector::Noon,
connector::Novalnet,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 0637b98163d..775cc91ebef 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -471,6 +471,9 @@ impl ConnectorData {
enums::Connector::Nexinets => {
Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets)))
}
+ // enums::Connector::Nexixpay => {
+ // Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay)))
+ // }
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 99ddd1cd1ab..5d5e72efd15 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -301,6 +301,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
})?
}
api_enums::Connector::Nexinets => Self::Nexinets,
+ // api_enums::Connector::Nexixpay => Self::Nexixpay,
api_enums::Connector::Nmi => Self::Nmi,
api_enums::Connector::Noon => Self::Noon,
// api_enums::Connector::Novalnet => Self::Novalnet,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 2a400b947dc..9b2b7d9ca04 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -45,6 +45,7 @@ mod mollie;
mod multisafepay;
mod netcetera;
mod nexinets;
+mod nexixpay;
mod nmi;
mod noon;
mod novalnet;
diff --git a/crates/router/tests/connectors/nexixpay.rs b/crates/router/tests/connectors/nexixpay.rs
new file mode 100644
index 00000000000..ebb68dd2898
--- /dev/null
+++ b/crates/router/tests/connectors/nexixpay.rs
@@ -0,0 +1,421 @@
+use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct NexixpayTest;
+impl ConnectorActions for NexixpayTest {}
+impl utils::Connector for NexixpayTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Nexixpay;
+ utils::construct_connector_data_old(
+ Box::new(Nexixpay::new()),
+ types::Connector::Plaid,
+ api::GetToken::Connector,
+ None,
+ )
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .nexixpay
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "nexixpay".to_string()
+ }
+}
+
+static CONNECTOR: NexixpayTest = NexixpayTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 6134d1ae036..1fa302c7161 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -261,6 +261,9 @@ api_key="API Key"
[fiservemea]
api_key="API Key"
+[nexixpay]
+api_key="API Key"
+
[wellsfargopayout]
api_key = "Consumer Key"
key1 = "Gateway Entity Id"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 3bf191d3e76..8e7a041f2d7 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -50,6 +50,7 @@ pub struct ConnectorAuthentication {
pub multisafepay: Option<HeaderKey>,
pub netcetera: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
+ pub nexixpay: Option<HeaderKey>,
pub noon: Option<SignatureKey>,
pub novalnet: Option<HeaderKey>,
pub nmi: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 347d587014d..efdef8fc88d 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -116,10 +116,11 @@ mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch"
nexinets.base_url = "https://apitest.payengine.de/v1"
+nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
nmi.base_url = "https://secure.nmi.com/"
noon.base_url = "https://api-test.noonpayments.com/"
-novalnet.base_url = "https://payport.novalnet.de/v2"
noon.key_mode = "Test"
+novalnet.base_url = "https://payport.novalnet.de/v2"
nuvei.base_url = "https://ppp-test.nuvei.com/"
opayo.base_url = "https://pi-test.sagepay.com/"
opennode.base_url = "https://dev-api.opennode.com"
@@ -201,6 +202,7 @@ cards = [
"multisafepay",
"netcetera",
"nexinets",
+ "nexixpay",
"nmi",
"noon",
"novalnet",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 362d0577c69..f9aa336300f 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
feat
|
[NEXIXPAY] Add template code (#5684)
|
36cc0ccbe69dc8f43c4cdd6daaea5e07beea8514
|
2024-08-22 20:25:09
|
AkshayaFoiger
|
feat(router): [cybersource] add disable_avs and disable_cvn flag in connector metadata (#5667)
| false
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index cc2ad85e56c..6f16d4f5c1a 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1217,6 +1217,9 @@ key1="Merchant ID"
api_secret="Shared Secret"
[cybersource.connector_webhook_details]
merchant_secret="Source verification key"
+[cybersource.metadata]
+disable_avs = "Disable AVS check"
+disable_cvn = "Disable CVN check"
[[cybersource.metadata.apple_pay]]
name="certificate"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index a61911b9da1..966becc1950 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1032,6 +1032,9 @@ key1="Merchant ID"
api_secret="Shared Secret"
[cybersource.connector_webhook_details]
merchant_secret="Source verification key"
+[cybersource.metadata]
+disable_avs = "Disable AVS check"
+disable_cvn = "Disable CVN check"
[[cybersource.metadata.apple_pay]]
name="certificate"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index b61187def75..a2f01b0b459 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1217,6 +1217,9 @@ key1="Merchant ID"
api_secret="Shared Secret"
[cybersource.connector_webhook_details]
merchant_secret="Source verification key"
+[cybersource.metadata]
+disable_avs = "Disable AVS check"
+disable_cvn = "Disable CVN check"
[[cybersource.metadata.apple_pay]]
name="certificate"
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 67f88e24ab3..2375dd578b3 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -54,6 +54,23 @@ impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for CybersourceRo
}
}
+#[derive(Debug, Default, Serialize, Deserialize)]
+pub struct CybersourceConnectorMetadataObject {
+ pub disable_avs: Option<bool>,
+ pub disable_cvn: Option<bool>,
+}
+
+impl TryFrom<&Option<pii::SecretSerdeValue>> for CybersourceConnectorMetadataObject {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
+ let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ Ok(metadata)
+ }
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceZeroMandateRequest {
@@ -76,6 +93,9 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
},
bill_to: Some(bill_to),
};
+ let connector_merchant_config =
+ CybersourceConnectorMetadataObject::try_from(&item.connector_meta_data)?;
+
let (action_list, action_token_types, authorization_options) = (
Some(vec![CybersourceActionsList::TokenCreate]),
Some(vec![
@@ -89,6 +109,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
stored_credential_used: None,
}),
merchant_intitiated_transaction: None,
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
}),
);
@@ -310,6 +332,8 @@ pub enum CybersourceActionsTokenType {
pub struct CybersourceAuthorizationOptions {
initiator: Option<CybersourcePaymentInitiator>,
merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>,
+ ignore_avs_result: Option<bool>,
+ ignore_cv_result: Option<bool>,
}
#[derive(Debug, Serialize)]
@@ -548,6 +572,9 @@ impl
.unwrap_or("internet")
.to_string();
+ let connector_merchant_config =
+ CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
+
let (action_list, action_token_types, authorization_options) = if item
.router_data
.request
@@ -576,6 +603,8 @@ impl
credential_stored_on_file: Some(true),
stored_credential_used: None,
}),
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
merchant_intitiated_transaction: None,
}),
)
@@ -624,6 +653,8 @@ impl
original_authorized_amount,
previous_transaction_id: None,
}),
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
}
@@ -690,13 +721,24 @@ impl
original_authorized_amount,
previous_transaction_id: Some(Secret::new(network_transaction_id)),
}),
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
}
None => (None, None, None),
}
} else {
- (None, None, None)
+ (
+ None,
+ None,
+ Some(CybersourceAuthorizationOptions {
+ initiator: None,
+ merchant_intitiated_transaction: None,
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
+ }),
+ )
};
// this logic is for external authenticated card
let commerce_indicator_for_external_authentication = item
@@ -778,19 +820,23 @@ fn get_commerce_indicator_for_external_authentication(
}
impl
- From<(
+ TryFrom<(
&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
&CybersourceConsumerAuthValidateResponse,
)> for ProcessingInformation
{
- fn from(
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
(item, solution, three_ds_data): (
&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
&CybersourceConsumerAuthValidateResponse,
),
- ) -> Self {
+ ) -> Result<Self, Self::Error> {
+ let connector_merchant_config =
+ CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
+
let (action_list, action_token_types, authorization_options) = if item
.router_data
.request
@@ -813,12 +859,14 @@ impl
stored_credential_used: None,
}),
merchant_intitiated_transaction: None,
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
} else {
(None, None, None)
};
- Self {
+ Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
@@ -832,7 +880,7 @@ impl
.indicator
.to_owned()
.unwrap_or(String::from("internet")),
- }
+ })
}
}
@@ -1100,7 +1148,7 @@ impl
})?;
let processing_information =
- ProcessingInformation::from((item, None, &three_ds_info.three_ds_data));
+ ProcessingInformation::try_from((item, None, &three_ds_info.three_ds_data))?;
let consumer_authentication_information = Some(CybersourceConsumerAuthInformation {
ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator,
@@ -1585,6 +1633,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout
fn try_from(
item: &CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRouterData>,
) -> Result<Self, Self::Error> {
+ let connector_merchant_config =
+ CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
+
Ok(Self {
processing_information: ProcessingInformation {
action_list: None,
@@ -1600,6 +1651,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout
previous_transaction_id: None,
original_authorized_amount: None,
}),
+ ignore_avs_result: connector_merchant_config.disable_avs,
+ ignore_cv_result: connector_merchant_config.disable_cvn,
}),
commerce_indicator: String::from("internet"),
capture: None,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index e68b31ea43a..3f2d2142d37 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1329,6 +1329,9 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
}
api_enums::Connector::Cybersource => {
cybersource::transformers::CybersourceAuthType::try_from(self.auth_type)?;
+ cybersource::transformers::CybersourceConnectorMetadataObject::try_from(
+ self.connector_meta_data,
+ )?;
Ok(())
}
api_enums::Connector::Datatrans => {
|
feat
|
[cybersource] add disable_avs and disable_cvn flag in connector metadata (#5667)
|
c20ecb855aa3c4b3ce1798dcc19910fb38345b46
|
2024-04-29 17:55:01
|
Apoorv Dixit
|
feat(user): add single purpose token and auth (#4470)
| false
|
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 03db3987eaa..8652f51451a 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
+ }
+}
|
feat
|
add single purpose token and auth (#4470)
|
6dd61b62ef322462e1a592e2dd3ef31683507f65
|
2023-07-03 17:15:42
|
Shreyash Kumar Pandey
|
refactor(payments_start): remove redundant call to fetch payment method data (#1574)
| false
|
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 9490213a39a..e05e0a02608 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -242,14 +242,14 @@ where
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
- state: &'a AppState,
- payment_data: &mut PaymentData<F>,
+ _state: &'a AppState,
+ _payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsStartRequest>,
Option<api::PaymentMethodData>,
)> {
- helpers::make_pm_data(Box::new(self), state, payment_data).await
+ Ok((Box::new(self), None))
}
async fn get_connector<'a>(
|
refactor
|
remove redundant call to fetch payment method data (#1574)
|
87f0537743b79953d115b7a7beb4d5e54404f82c
|
2023-01-12 15:51:32
|
Narayan Bhat
|
fix(gpay): send merchant info field (#358)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 8dce41e2829..2440d7750da 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -819,7 +819,7 @@ pub struct GpayMetadata {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GpaySessionTokenData {
- pub gpay: GpayMetadata,
+ pub data: GpayMetadata,
}
#[derive(Debug, Clone, serde::Serialize)]
@@ -827,7 +827,8 @@ pub struct GpaySessionTokenData {
#[serde(rename_all = "lowercase")]
pub enum SessionToken {
Gpay {
- allowed_payment_methods: Vec<GpayAllowedPaymentMethods>,
+ #[serde(flatten)]
+ data: GpayMetadata,
transaction_info: GpayTransactionInfo,
},
Klarna {
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index c0cdaffefc7..af6b96c8304 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -84,7 +84,7 @@ fn create_gpay_session_token(
let response_router_data = types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Gpay {
- allowed_payment_methods: gpay_data.gpay.allowed_payment_methods,
+ data: gpay_data.data,
transaction_info,
},
}),
|
fix
|
send merchant info field (#358)
|
f091be60cc628eff4a3537cd6f5d00402a08650d
|
2023-07-01 15:27:33
|
Swangi Kumari
|
feat(connector): [Mollie] Implement Przelewy24 and BancontactCard Bank Redirects for Mollie connector (#1303)
| false
|
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index c8e6dad6db2..e4f47ec93ae 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -1,4 +1,5 @@
use api_models::payments;
+use common_utils::pii::Email;
use error_stack::IntoReport;
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -46,6 +47,8 @@ pub enum PaymentMethodData {
Ideal(Box<IdealMethodData>),
Paypal(Box<PaypalMethodData>),
Sofort,
+ Przelewy24(Box<Przelewy24MethodData>),
+ Bancontact,
DirectDebit(Box<DirectDebitMethodData>),
}
@@ -68,6 +71,12 @@ pub struct PaypalMethodData {
shipping_address: Option<Address>,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Przelewy24MethodData {
+ billing_email: Option<Email>,
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectDebitMethodData {
@@ -159,6 +168,12 @@ impl TryFrom<&api_models::payments::BankRedirectData> for PaymentMethodData {
})))
}
api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ api_models::payments::BankRedirectData::Przelewy24 {
+ billing_details, ..
+ } => Ok(Self::Przelewy24(Box::new(Przelewy24MethodData {
+ billing_email: billing_details.email.clone(),
+ }))),
+ api_models::payments::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
diff --git a/crates/router/tests/connectors/mollie_ui.rs b/crates/router/tests/connectors/mollie_ui.rs
index 61ec5a7acc7..15855b86810 100644
--- a/crates/router/tests/connectors/mollie_ui.rs
+++ b/crates/router/tests/connectors/mollie_ui.rs
@@ -130,6 +130,52 @@ async fn should_make_mollie_giropay_payment(c: WebDriver) -> Result<(), WebDrive
Ok(())
}
+async fn should_make_mollie_bancontact_card_payment(c: WebDriver) -> Result<(), WebDriverError> {
+ let conn = MollieSeleniumTest {};
+ conn.make_redirection_payment(
+ c,
+ vec![
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/86"))),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ Event::Assert(Assert::IsPresent("Test profile")),
+ Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
+ Event::Trigger(Trigger::Click(By::Css(
+ "button[class='button form__button']",
+ ))),
+ Event::Assert(Assert::IsPresent("Google")),
+ Event::Assert(Assert::Contains(
+ Selector::QueryParamStr,
+ "status=succeeded",
+ )),
+ ],
+ )
+ .await?;
+ Ok(())
+}
+
+async fn should_make_mollie_przelewy24_payment(c: WebDriver) -> Result<(), WebDriverError> {
+ let conn = MollieSeleniumTest {};
+ conn.make_redirection_payment(
+ c,
+ vec![
+ Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/87"))),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ Event::Assert(Assert::IsPresent("Test profile")),
+ Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
+ Event::Trigger(Trigger::Click(By::Css(
+ "button[class='button form__button']",
+ ))),
+ Event::Assert(Assert::IsPresent("Google")),
+ Event::Assert(Assert::Contains(
+ Selector::QueryParamStr,
+ "status=succeeded",
+ )),
+ ],
+ )
+ .await?;
+ Ok(())
+}
+
#[test]
#[serial]
fn should_make_mollie_paypal_payment_test() {
@@ -159,3 +205,15 @@ fn should_make_mollie_eps_payment_test() {
fn should_make_mollie_giropay_payment_test() {
tester!(should_make_mollie_giropay_payment);
}
+
+#[test]
+#[serial]
+fn should_make_mollie_bancontact_card_payment_test() {
+ tester!(should_make_mollie_bancontact_card_payment);
+}
+
+#[test]
+#[serial]
+fn should_make_mollie_przelewy24_payment_test() {
+ tester!(should_make_mollie_przelewy24_payment);
+}
diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs
index 5936350dc82..6b54dd661bf 100644
--- a/crates/router/tests/connectors/selenium.rs
+++ b/crates/router/tests/connectors/selenium.rs
@@ -504,18 +504,23 @@ pub fn make_capabilities(s: &str) -> Capabilities {
}
}
fn get_chrome_profile_path() -> Result<String, WebDriverError> {
- let exe = env::current_exe()?;
- let dir = exe.parent().expect("Executable must be in some directory");
- let mut base_path = dir
- .to_str()
- .map(|str| {
- let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>();
- fp.truncate(3);
- fp.join(&MAIN_SEPARATOR.to_string())
- })
- .unwrap();
- base_path.push_str(r#"/Library/Application\ Support/Google/Chrome/Default"#);
- Ok(base_path)
+ env::var("CHROME_PROFILE_PATH").map_or_else(
+ |_| -> Result<String, WebDriverError> {
+ let exe = env::current_exe()?;
+ let dir = exe.parent().expect("Executable must be in some directory");
+ let mut base_path = dir
+ .to_str()
+ .map(|str| {
+ let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>();
+ fp.truncate(3);
+ fp.join(&MAIN_SEPARATOR.to_string())
+ })
+ .unwrap();
+ base_path.push_str(r#"/Library/Application\ Support/Google/Chrome/Default"#);
+ Ok(base_path)
+ },
+ Ok,
+ )
}
fn get_firefox_profile_path() -> Result<String, WebDriverError> {
let exe = env::current_exe()?;
|
feat
|
[Mollie] Implement Przelewy24 and BancontactCard Bank Redirects for Mollie connector (#1303)
|
afd7f7d20980f6f39673008c86b89b1e501f05f2
|
2024-11-14 14:09:30
|
Uzair Khan
|
feat(analytics): add `sessionized_metrics` and `currency_conversion` for refunds analytics (#6419)
| false
|
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index 64ca7c3f82b..3654cad8c09 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -69,11 +69,21 @@ pub async fn get_sankey(
i.refunds_status.unwrap_or_default().as_ref(),
i.attempt_count,
) {
+ (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, 1) => {
+ sankey_response.refunded += i.count;
+ sankey_response.normal_success += i.count
+ }
+ (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, 1) => {
+ sankey_response.partial_refunded += i.count;
+ sankey_response.normal_success += i.count
+ }
(IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, _) => {
- sankey_response.refunded += i.count
+ sankey_response.refunded += i.count;
+ sankey_response.smart_retried_success += i.count
}
(IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, _) => {
- sankey_response.partial_refunded += i.count
+ sankey_response.partial_refunded += i.count;
+ sankey_response.smart_retried_success += i.count
}
(
IntentStatus::Succeeded
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs
index 651eeb0bcfe..5ca9fdf7516 100644
--- a/crates/analytics/src/payments/accumulator.rs
+++ b/crates/analytics/src/payments/accumulator.rs
@@ -387,7 +387,7 @@ impl PaymentMetricsAccumulator {
payment_processed_count,
payment_processed_amount_without_smart_retries,
payment_processed_count_without_smart_retries,
- payment_processed_amount_usd,
+ payment_processed_amount_in_usd,
payment_processed_amount_without_smart_retries_usd,
) = self.processed_amount.collect();
let (
@@ -417,7 +417,7 @@ impl PaymentMetricsAccumulator {
payments_failure_rate_distribution_without_smart_retries,
failure_reason_count,
failure_reason_count_without_smart_retries,
- payment_processed_amount_usd,
+ payment_processed_amount_in_usd,
payment_processed_amount_without_smart_retries_usd,
}
}
diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs
index bcd009270dc..01a3b1abc15 100644
--- a/crates/analytics/src/payments/core.rs
+++ b/crates/analytics/src/payments/core.rs
@@ -228,7 +228,7 @@ pub async fn get_metrics(
let mut total_payment_processed_count_without_smart_retries = 0;
let mut total_failure_reasons_count = 0;
let mut total_failure_reasons_count_without_smart_retries = 0;
- let mut total_payment_processed_amount_usd = 0;
+ let mut total_payment_processed_amount_in_usd = 0;
let mut total_payment_processed_amount_without_smart_retries_usd = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
@@ -251,9 +251,9 @@ pub async fn get_metrics(
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default();
- collected_values.payment_processed_amount_usd = amount_in_usd;
+ collected_values.payment_processed_amount_in_usd = amount_in_usd;
total_payment_processed_amount += amount;
- total_payment_processed_amount_usd += amount_in_usd.unwrap_or(0);
+ total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count {
total_payment_processed_count += count;
@@ -299,7 +299,7 @@ pub async fn get_metrics(
query_data,
meta_data: [PaymentsAnalyticsMetadata {
total_payment_processed_amount: Some(total_payment_processed_amount),
- total_payment_processed_amount_usd: Some(total_payment_processed_amount_usd),
+ total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd),
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
diff --git a/crates/analytics/src/refunds/accumulator.rs b/crates/analytics/src/refunds/accumulator.rs
index 9c51defdcf9..add38c98162 100644
--- a/crates/analytics/src/refunds/accumulator.rs
+++ b/crates/analytics/src/refunds/accumulator.rs
@@ -7,7 +7,7 @@ pub struct RefundMetricsAccumulator {
pub refund_success_rate: SuccessRateAccumulator,
pub refund_count: CountAccumulator,
pub refund_success: CountAccumulator,
- pub processed_amount: SumAccumulator,
+ pub processed_amount: PaymentProcessedAmountAccumulator,
}
#[derive(Debug, Default)]
@@ -22,7 +22,7 @@ pub struct CountAccumulator {
}
#[derive(Debug, Default)]
#[repr(transparent)]
-pub struct SumAccumulator {
+pub struct PaymentProcessedAmountAccumulator {
pub total: Option<i64>,
}
@@ -50,8 +50,8 @@ impl RefundMetricAccumulator for CountAccumulator {
}
}
-impl RefundMetricAccumulator for SumAccumulator {
- type MetricOutput = Option<u64>;
+impl RefundMetricAccumulator for PaymentProcessedAmountAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
self.total = match (
@@ -68,7 +68,7 @@ impl RefundMetricAccumulator for SumAccumulator {
}
#[inline]
fn collect(self) -> Self::MetricOutput {
- self.total.and_then(|i| u64::try_from(i).ok())
+ (self.total.and_then(|i| u64::try_from(i).ok()), Some(0))
}
}
@@ -98,11 +98,14 @@ impl RefundMetricAccumulator for SuccessRateAccumulator {
impl RefundMetricsAccumulator {
pub fn collect(self) -> RefundMetricsBucketValue {
+ let (refund_processed_amount, refund_processed_amount_in_usd) =
+ self.processed_amount.collect();
RefundMetricsBucketValue {
refund_success_rate: self.refund_success_rate.collect(),
refund_count: self.refund_count.collect(),
refund_success_count: self.refund_success.collect(),
- refund_processed_amount: self.processed_amount.collect(),
+ refund_processed_amount,
+ refund_processed_amount_in_usd,
}
}
}
diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs
index 9c4770c79ee..e3bfa4da9d1 100644
--- a/crates/analytics/src/refunds/core.rs
+++ b/crates/analytics/src/refunds/core.rs
@@ -5,9 +5,12 @@ use api_models::analytics::{
refunds::{
RefundDimensions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse,
},
- AnalyticsMetadata, GetRefundFilterRequest, GetRefundMetricRequest, MetricsResponse,
- RefundFilterValue, RefundFiltersResponse,
+ GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse,
+ RefundsAnalyticsMetadata, RefundsMetricsResponse,
};
+use bigdecimal::ToPrimitive;
+use common_enums::Currency;
+use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
logger,
@@ -29,9 +32,10 @@ use crate::{
pub async fn get_metrics(
pool: &AnalyticsProvider,
+ ex_rates: &ExchangeRates,
auth: &AuthInfo,
req: GetRefundMetricRequest,
-) -> AnalyticsResult<MetricsResponse<RefundMetricsBucketResponse>> {
+) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> =
HashMap::new();
let mut set = tokio::task::JoinSet::new();
@@ -86,16 +90,20 @@ pub async fn get_metrics(
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
- RefundMetrics::RefundSuccessRate => metrics_builder
- .refund_success_rate
- .add_metrics_bucket(&value),
- RefundMetrics::RefundCount => {
+ RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => {
+ metrics_builder
+ .refund_success_rate
+ .add_metrics_bucket(&value)
+ }
+ RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => {
metrics_builder.refund_count.add_metrics_bucket(&value)
}
- RefundMetrics::RefundSuccessCount => {
+ RefundMetrics::RefundSuccessCount
+ | RefundMetrics::SessionizedRefundSuccessCount => {
metrics_builder.refund_success.add_metrics_bucket(&value)
}
- RefundMetrics::RefundProcessedAmount => {
+ RefundMetrics::RefundProcessedAmount
+ | RefundMetrics::SessionizedRefundProcessedAmount => {
metrics_builder.processed_amount.add_metrics_bucket(&value)
}
}
@@ -107,18 +115,45 @@ pub async fn get_metrics(
metrics_accumulator
);
}
+ let mut total_refund_processed_amount = 0;
+ let mut total_refund_processed_amount_in_usd = 0;
let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator
.into_iter()
- .map(|(id, val)| RefundMetricsBucketResponse {
- values: val.collect(),
- dimensions: id,
+ .map(|(id, val)| {
+ let mut collected_values = val.collect();
+ if let Some(amount) = collected_values.refund_processed_amount {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.refund_processed_amount_in_usd = amount_in_usd;
+ total_refund_processed_amount += amount;
+ total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
+ }
+ RefundMetricsBucketResponse {
+ values: collected_values,
+ dimensions: id,
+ }
})
.collect();
- Ok(MetricsResponse {
+ Ok(RefundsMetricsResponse {
query_data,
- meta_data: [AnalyticsMetadata {
- current_time_range: req.time_range,
+ meta_data: [RefundsAnalyticsMetadata {
+ total_refund_processed_amount: Some(total_refund_processed_amount),
+ total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd),
}],
})
}
diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs
index 6ecfd8aeb29..c211ea82d7a 100644
--- a/crates/analytics/src/refunds/metrics.rs
+++ b/crates/analytics/src/refunds/metrics.rs
@@ -10,6 +10,7 @@ mod refund_count;
mod refund_processed_amount;
mod refund_success_count;
mod refund_success_rate;
+mod sessionized_metrics;
use std::collections::HashSet;
use refund_count::RefundCount;
@@ -101,6 +102,26 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::SessionizedRefundSuccessRate => {
+ sessionized_metrics::RefundSuccessRate::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundCount => {
+ sessionized_metrics::RefundCount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundSuccessCount => {
+ sessionized_metrics::RefundSuccessCount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundProcessedAmount => {
+ sessionized_metrics::RefundProcessedAmount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
}
}
}
diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
index f0f51a21fe0..6cba5f58fed 100644
--- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
+++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
@@ -52,6 +52,7 @@ where
alias: Some("total"),
})
.switch()?;
+ query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
@@ -78,6 +79,7 @@ where
query_builder.add_group_by_clause(dim).switch()?;
}
+ query_builder.add_group_by_clause("currency").switch()?;
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs
new file mode 100644
index 00000000000..bb404cd3410
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs
@@ -0,0 +1,11 @@
+mod refund_count;
+mod refund_processed_amount;
+mod refund_success_count;
+mod refund_success_rate;
+
+pub(super) use refund_count::RefundCount;
+pub(super) use refund_processed_amount::RefundProcessedAmount;
+pub(super) use refund_success_count::RefundSuccessCount;
+pub(super) use refund_success_rate::RefundSuccessRate;
+
+pub use super::{RefundMetric, RefundMetricAnalytics, RefundMetricRow};
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
new file mode 100644
index 00000000000..c77e1f7a52c
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
@@ -0,0 +1,120 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundCount {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundCount
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ i.refund_status.as_ref().map(|i| i.0.to_string()),
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
new file mode 100644
index 00000000000..c91938228af
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
@@ -0,0 +1,129 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct RefundProcessedAmount {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundProcessedAmount
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "refund_amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+ query_builder.add_select_column("currency").switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ query_builder.add_group_by_clause("currency").switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ RefundDimensions::RefundStatus,
+ storage_enums::RefundStatus::Success,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
new file mode 100644
index 00000000000..332261a3208
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
@@ -0,0 +1,125 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundSuccessCount {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundSuccessCount
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range.set_filter_clause(&mut query_builder).switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ RefundDimensions::RefundStatus,
+ storage_enums::RefundStatus::Success,
+ )
+ .switch()?;
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
new file mode 100644
index 00000000000..35ee0d61b50
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
@@ -0,0 +1,120 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct RefundSuccessRate {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundSuccessRate
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(RefundDimensions::RefundStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range.set_filter_clause(&mut query_builder).switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 8d63bc3096c..70c0e0e78dc 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -203,7 +203,7 @@ pub struct AnalyticsMetadata {
#[derive(Debug, serde::Serialize)]
pub struct PaymentsAnalyticsMetadata {
pub total_payment_processed_amount: Option<u64>,
- pub total_payment_processed_amount_usd: Option<u64>,
+ pub total_payment_processed_amount_in_usd: Option<u64>,
pub total_payment_processed_amount_without_smart_retries: Option<u64>,
pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub total_payment_processed_count: Option<u64>,
@@ -228,6 +228,11 @@ pub struct PaymentIntentsAnalyticsMetadata {
pub total_payment_processed_count_without_smart_retries: Option<u64>,
}
+#[derive(Debug, serde::Serialize)]
+pub struct RefundsAnalyticsMetadata {
+ pub total_refund_processed_amount: Option<u64>,
+ pub total_refund_processed_amount_in_usd: Option<u64>,
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentFiltersRequest {
@@ -362,6 +367,12 @@ pub struct PaymentIntentsMetricsResponse<T> {
pub meta_data: [PaymentIntentsAnalyticsMetadata; 1],
}
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RefundsMetricsResponse<T> {
+ pub query_data: Vec<T>,
+ pub meta_data: [RefundsAnalyticsMetadata; 1],
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventFiltersRequest {
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index 1faba79eb37..b34f8c9293c 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -271,7 +271,7 @@ pub struct PaymentMetricsBucketValue {
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
- pub payment_processed_amount_usd: Option<u64>,
+ pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_usd: Option<u64>,
diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs
index ef17387d1ea..d981bd4382f 100644
--- a/crates/api_models/src/analytics/refunds.rs
+++ b/crates/api_models/src/analytics/refunds.rs
@@ -88,6 +88,10 @@ pub enum RefundMetrics {
RefundCount,
RefundSuccessCount,
RefundProcessedAmount,
+ SessionizedRefundSuccessRate,
+ SessionizedRefundCount,
+ SessionizedRefundSuccessCount,
+ SessionizedRefundProcessedAmount,
}
pub mod metric_behaviour {
@@ -176,6 +180,7 @@ pub struct RefundMetricsBucketValue {
pub refund_count: Option<u64>,
pub refund_success_count: Option<u64>,
pub refund_processed_amount: Option<u64>,
+ pub refund_processed_amount_in_usd: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketResponse {
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 7272abffbff..77d8cb117ef 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -168,6 +168,11 @@ impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> {
}
}
+impl<T> ApiEventMetric for RefundsMetricsResponse<T> {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Miscellaneous)
+ }
+}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index e0808b92260..a13f476950b 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -659,7 +659,8 @@ pub mod routes {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
- analytics::refunds::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -697,7 +698,8 @@ pub mod routes {
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
- analytics::refunds::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -743,7 +745,8 @@ pub mod routes {
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
- analytics::refunds::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
|
feat
|
add `sessionized_metrics` and `currency_conversion` for refunds analytics (#6419)
|
2f0005ae382fcbcb941d179f0a0d2dd5f93f724a
|
2025-03-11 14:55:08
|
Susritha
|
chore(wasm): show allowed auth methods option in google pay (#7425)
| false
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 2708fe11af5..b63c4eea2a1 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -297,6 +297,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[adyen.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[adyen.metadata.endpoint_prefix]
name="endpoint_prefix"
@@ -381,6 +388,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[airwallex.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[authorizedotnet]
@@ -500,6 +514,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[authorizedotnet.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bambora]
[[bambora.credit]]
@@ -703,6 +724,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[bankofamerica.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bitpay]
[[bitpay.crypto]]
@@ -829,6 +857,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[bluesnap.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bluesnap.metadata.merchant_id]
name="merchant_id"
@@ -1131,6 +1166,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[checkout.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[checkout.metadata.acquirer_bin]
name="acquirer_bin"
@@ -1299,6 +1341,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[cybersource.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[cybersource.connector_wallets_details.samsung_pay]]
name="service_id"
@@ -1691,6 +1740,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[globalpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[globalpay.metadata.account_name]
name="account_name"
@@ -1983,6 +2039,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[multisafepay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[nexinets]
[[nexinets.credit]]
@@ -2230,6 +2293,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[nmi.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[nmi.metadata.acquirer_bin]
name="acquirer_bin"
@@ -2370,6 +2440,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[noon.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[novalnet]
[[novalnet.credit]]
@@ -2438,6 +2515,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[novalnet.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[novalnet.metadata.apple_pay]]
name="certificate"
@@ -2624,6 +2708,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[nuvei.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[opennode]
@@ -2818,6 +2909,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[payu.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[placetopay]
[[placetopay.credit]]
@@ -3275,6 +3373,13 @@ label="Stripe Publishable Key"
placeholder="Enter Stripe Publishable Key"
required=true
type="Text"
+[[stripe.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[stax]
[[stax.credit]]
@@ -3491,6 +3596,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[trustpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[tsys]
@@ -3720,6 +3832,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[worldpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[zen]
[[zen.credit]]
@@ -4409,6 +4528,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[fiuu.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[fiuu.metadata.apple_pay]]
name="certificate"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 52535d57b4a..a2e01c524e8 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -198,6 +198,13 @@ label="Google Pay Merchant Id"
placeholder="Enter Google Pay Merchant Id"
required=true
type="Text"
+[[adyen.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[adyen.metadata.endpoint_prefix]
name="endpoint_prefix"
@@ -368,6 +375,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[authorizedotnet.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bitpay]
[[bitpay.crypto]]
@@ -493,6 +507,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[bluesnap.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bluesnap.metadata.merchant_id]
name="merchant_id"
@@ -763,6 +784,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[bankofamerica.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[cashtocode]
[[cashtocode.reward]]
@@ -986,6 +1014,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[checkout.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[coinbase]
@@ -1124,6 +1159,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[cybersource.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[cybersource.metadata.acquirer_bin]
name="acquirer_bin"
@@ -1416,6 +1458,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[globalpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[globalpay.metadata.account_name]
name="account_name"
@@ -1907,6 +1956,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[novalnet.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[novalnet.metadata.apple_pay]]
name="certificate"
@@ -2130,6 +2186,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[payu.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[rapyd]
[[rapyd.credit]]
@@ -2421,7 +2484,13 @@ label="Stripe Publishable Key"
placeholder="Enter Stripe Publishable Key"
required=true
type="Text"
-
+[[stripe.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
@@ -2552,6 +2621,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[trustpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[worldline]
[[worldline.credit]]
@@ -2722,6 +2798,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[worldpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[payme]
@@ -3330,6 +3413,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[fiuu.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[fiuu.metadata.apple_pay]]
name="certificate"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index da8f9ba62e5..8084bd00b00 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -296,6 +296,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[adyen.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[adyen.metadata.endpoint_prefix]
name="endpoint_prefix"
@@ -382,6 +389,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[airwallex.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[authorizedotnet]
@@ -502,6 +516,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[authorizedotnet.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bambora]
[[bambora.credit]]
@@ -703,6 +724,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[bankofamerica.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bitpay]
[[bitpay.crypto]]
@@ -828,6 +856,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[bluesnap.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[bluesnap.metadata.merchant_id]
name="merchant_id"
@@ -1129,6 +1164,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[checkout.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[checkout.metadata.acquirer_bin]
name="acquirer_bin"
@@ -1296,6 +1338,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[cybersource.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[cybersource.metadata.acquirer_bin]
name="acquirer_bin"
@@ -1641,6 +1690,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[globalpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[globalpay.metadata.account_name]
name="account_name"
@@ -1934,6 +1990,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[multisafepay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[nexinets]
[[nexinets.credit]]
@@ -2179,6 +2242,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[nmi.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[nmi.metadata.acquirer_bin]
name="acquirer_bin"
@@ -2318,6 +2388,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[noon.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[novalnet]
[[novalnet.credit]]
@@ -2386,6 +2463,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[novalnet.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[novalnet.metadata.apple_pay]]
name="certificate"
@@ -2570,6 +2654,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[nuvei.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[opennode]
@@ -2764,6 +2855,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[payu.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[placetopay]
[[placetopay.credit]]
@@ -3218,6 +3316,13 @@ label="Stripe Publishable Key"
placeholder="Enter Stripe Publishable Key"
required=true
type="Text"
+[[stripe.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[stax]
[[stax.credit]]
@@ -3433,6 +3538,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[trustpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[tsys]
[[tsys.credit]]
@@ -3660,6 +3772,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[worldpay.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[zen]
[[zen.credit]]
@@ -4350,6 +4469,13 @@ label="Google Pay Merchant Key"
placeholder="Enter Google Pay Merchant Key"
required=true
type="Text"
+[[fiuu.metadata.google_pay]]
+name="allowed_auth_methods"
+label="Allowed Auth Methods"
+placeholder="Enter Allowed Auth Methods"
+required=true
+type="MultiSelect"
+options=["PAN_ONLY", "CRYPTOGRAM_3DS"]
[[fiuu.metadata.apple_pay]]
name="certificate"
|
chore
|
show allowed auth methods option in google pay (#7425)
|
e393a036fbde109d367e488807a53e919a12db90
|
2024-12-27 13:39:42
|
Debarati Ghatak
|
feat(connector): [Fiuu] Consume error message thrown by connector for Psync flow and make extraP from response struct Secret (#6934)
| false
|
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu.rs b/crates/hyperswitch_connectors/src/connectors/fiuu.rs
index 7805281c4be..3ea8793d9f5 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu.rs
@@ -908,7 +908,7 @@ impl webhooks::IncomingWebhook for Fiuu {
serde_urlencoded::from_bytes::<transformers::FiuuWebhooksPaymentResponse>(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let mandate_reference = webhook_payment_response.extra_parameters.as_ref().and_then(|extra_p| {
- let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(extra_p);
+ let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(&extra_p.clone().expose());
match mandate_token {
Ok(token) => {
token.token.as_ref().map(|token| hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails {
@@ -918,7 +918,7 @@ impl webhooks::IncomingWebhook for Fiuu {
Err(err) => {
router_env::logger::warn!(
"Failed to convert 'extraP' from fiuu webhook response to fiuu::ExtraParameters. \
- Input: '{}', Error: {}",
+ Input: '{:?}', Error: {}",
extra_p,
err
);
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index 143cd1aa047..14ce13f971b 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -1168,9 +1168,9 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
let error_response = if status == enums::AttemptStatus::Failure {
Some(ErrorResponse {
status_code: item.http_code,
- code: response.stat_code.to_string(),
- message: response.stat_name.clone().to_string(),
- reason: Some(response.stat_name.clone().to_string()),
+ code: response.error_code.clone(),
+ message: response.error_desc.clone(),
+ reason: Some(response.error_desc),
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: None,
})
@@ -1199,7 +1199,7 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
status: response.status,
})?;
let mandate_reference = response.extra_parameters.as_ref().and_then(|extra_p| {
- let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(extra_p);
+ let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(&extra_p.clone().expose());
match mandate_token {
Ok(token) => {
token.token.as_ref().map(|token| MandateReference {
@@ -1212,7 +1212,7 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
Err(err) => {
router_env::logger::warn!(
"Failed to convert 'extraP' from fiuu webhook response to fiuu::ExtraParameters. \
- Input: '{}', Error: {}",
+ Input: '{:?}', Error: {}",
extra_p,
err
);
@@ -1228,7 +1228,7 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_owned()),
message: response
- .error_code
+ .error_desc
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_owned()),
reason: response.error_desc.clone(),
@@ -1697,7 +1697,7 @@ pub struct FiuuWebhooksPaymentResponse {
pub error_desc: Option<String>,
pub error_code: Option<String>,
#[serde(rename = "extraP")]
- pub extra_parameters: Option<String>,
+ pub extra_parameters: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
|
feat
|
[Fiuu] Consume error message thrown by connector for Psync flow and make extraP from response struct Secret (#6934)
|
fea5c4d8c186f3b4e732f7d503e49724c3e4d308
|
2023-09-12 12:43:20
|
Sai Harsha Vardhan
|
feat(router): disable temp locker call for connector-payment_method flow based on env (#2120)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 2d84d4f3843..2a280f320f9 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -311,6 +311,10 @@ 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" }
+[temp_locker_disable_config]
+trustpay = {payment_method = "card,bank_redirect,wallet"}
+stripe = {payment_method = "card,bank_redirect,pay_later,wallet,bank_debit"}
+
[dummy_connector]
payment_ttl = 172800 # Time to live for dummy connector payment in redis
payment_duration = 1000 # Fake delay duration for dummy connector payment
diff --git a/config/development.toml b/config/development.toml
index 44eba5f93d4..9fc9dae8a2e 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -373,6 +373,10 @@ square = {long_lived_token = false, payment_method = "card"}
braintree = { long_lived_token = false, payment_method = "card" }
payme = {long_lived_token = false, payment_method = "card"}
+[temp_locker_disable_config]
+trustpay = {payment_method = "card,bank_redirect,wallet"}
+stripe = {payment_method = "card,bank_redirect,pay_later,wallet,bank_debit"}
+
[connector_customer]
connector_list = "bluesnap,stax,stripe"
payout_connector_list = "wise"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index adc41e1bb37..d2152cbb473 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -202,6 +202,10 @@ 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" }
+[temp_locker_disable_config]
+trustpay = {payment_method = "card,bank_redirect,wallet"}
+stripe = {payment_method = "card,bank_redirect,pay_later,wallet,bank_debit"}
+
[dummy_connector]
payment_ttl = 172800
payment_duration = 1000
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 3739afc7671..640f692d551 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -97,6 +97,7 @@ pub struct Settings {
pub applepay_decrypt_keys: ApplePayDecryptConifg,
pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,
pub applepay_merchant_configs: ApplepayMerchantConfigs,
+ pub temp_locker_disable_config: TempLockerDisableConfig,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -118,6 +119,10 @@ pub struct MultipleApiVersionSupportedConnectors {
#[serde(transparent)]
pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>);
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(transparent)]
+pub struct TempLockerDisableConfig(pub HashMap<String, TempLockerDisablePaymentMethodFilter>);
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorCustomer {
#[serde(deserialize_with = "connector_deser")]
@@ -207,6 +212,12 @@ pub struct PaymentMethodTokenFilter {
pub long_lived_token: bool,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct TempLockerDisablePaymentMethodFilter {
+ #[serde(deserialize_with = "pm_deser")]
+ pub payment_method: HashSet<diesel_models::enums::PaymentMethod>,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(
deny_unknown_fields,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 892f8fe2396..6efba6aa81c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -35,7 +35,7 @@ use super::{
#[cfg(feature = "kms")]
use crate::connector;
use crate::{
- configs::settings::{ConnectorRequestReferenceIdConfig, Server},
+ configs::settings::{ConnectorRequestReferenceIdConfig, Server, TempLockerDisableConfig},
consts::{self, BASE64_ENGINE},
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
@@ -1294,17 +1294,22 @@ pub async fn make_pm_data<'a, F: Clone, R>(
})
}
(pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)), _) => {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
+ if should_store_payment_method_data_in_vault(
+ &state.conf.temp_locker_disable_config,
+ payment_data.payment_attempt.connector.clone(),
enums::PaymentMethod::Card,
- )
- .await?;
-
- payment_data.token = Some(parent_payment_method_token);
+ ) {
+ let parent_payment_method_token = store_in_vault_and_generate_ppmt(
+ state,
+ pm,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ enums::PaymentMethod::Card,
+ )
+ .await?;
+ payment_data.token = Some(parent_payment_method_token);
+ }
Ok(pm_opt.to_owned())
}
(pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()),
@@ -1316,42 +1321,60 @@ pub async fn make_pm_data<'a, F: Clone, R>(
(pm @ Some(api::PaymentMethodData::CardRedirect(_)), _) => Ok(pm.to_owned()),
(pm @ Some(api::PaymentMethodData::GiftCard(_)), _) => Ok(pm.to_owned()),
(pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)), _) => {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
+ if should_store_payment_method_data_in_vault(
+ &state.conf.temp_locker_disable_config,
+ payment_data.payment_attempt.connector.clone(),
enums::PaymentMethod::BankTransfer,
- )
- .await?;
+ ) {
+ let parent_payment_method_token = store_in_vault_and_generate_ppmt(
+ state,
+ pm,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ enums::PaymentMethod::BankTransfer,
+ )
+ .await?;
- payment_data.token = Some(parent_payment_method_token);
+ payment_data.token = Some(parent_payment_method_token);
+ }
Ok(pm_opt.to_owned())
}
(pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)), _) => {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
+ if should_store_payment_method_data_in_vault(
+ &state.conf.temp_locker_disable_config,
+ payment_data.payment_attempt.connector.clone(),
enums::PaymentMethod::Wallet,
- )
- .await?;
+ ) {
+ let parent_payment_method_token = store_in_vault_and_generate_ppmt(
+ state,
+ pm,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ enums::PaymentMethod::Wallet,
+ )
+ .await?;
- payment_data.token = Some(parent_payment_method_token);
+ payment_data.token = Some(parent_payment_method_token);
+ }
Ok(pm_opt.to_owned())
}
(pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)), _) => {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
+ if should_store_payment_method_data_in_vault(
+ &state.conf.temp_locker_disable_config,
+ payment_data.payment_attempt.connector.clone(),
enums::PaymentMethod::BankRedirect,
- )
- .await?;
- payment_data.token = Some(parent_payment_method_token);
+ ) {
+ let parent_payment_method_token = store_in_vault_and_generate_ppmt(
+ state,
+ pm,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ enums::PaymentMethod::BankRedirect,
+ )
+ .await?;
+ payment_data.token = Some(parent_payment_method_token);
+ }
Ok(pm_opt.to_owned())
}
_ => Ok(None),
@@ -1390,6 +1413,23 @@ pub async fn store_in_vault_and_generate_ppmt(
Ok(parent_payment_method_token)
}
+pub fn should_store_payment_method_data_in_vault(
+ temp_locker_disable_config: &TempLockerDisableConfig,
+ option_connector: Option<String>,
+ payment_method: enums::PaymentMethod,
+) -> bool {
+ option_connector
+ .map(|connector| {
+ temp_locker_disable_config
+ .0
+ .get(&connector)
+ //should be true only if payment_method is not in the disable payment_method list for connector
+ .map(|config| !config.payment_method.contains(&payment_method))
+ .unwrap_or(true)
+ })
+ .unwrap_or(true)
+}
+
#[instrument(skip_all)]
pub(crate) fn validate_capture_method(
capture_method: storage_enums::CaptureMethod,
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 c06c8e4e776..18315969d22 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -108,13 +108,24 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
let token = token.or_else(|| payment_attempt.payment_token.clone());
- helpers::validate_pm_or_token_given(
- &request.payment_method,
- &request.payment_method_data,
- &request.payment_method_type,
- &mandate_type,
- &token,
- )?;
+ if let Some(payment_method) = payment_method {
+ let should_validate_pm_or_token_given =
+ //this validation should happen if data was stored in the vault
+ helpers::should_store_payment_method_data_in_vault(
+ &state.conf.temp_locker_disable_config,
+ payment_attempt.connector.clone(),
+ payment_method,
+ );
+ if should_validate_pm_or_token_given {
+ helpers::validate_pm_or_token_given(
+ &request.payment_method,
+ &request.payment_method_data,
+ &request.payment_method_type,
+ &mandate_type,
+ &token,
+ )?;
+ }
+ }
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info;
|
feat
|
disable temp locker call for connector-payment_method flow based on env (#2120)
|
2d839170fe889051772f5d99cdaff33573b4fb20
|
2023-08-08 16:44:40
|
Prajjwal Kumar
|
fix(router): add `serde(transparent)` annotation for `PaymentMethodMetadata` (#1899)
| false
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 9dab92f67fe..571b55e9e56 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1831,7 +1831,7 @@ pub async fn list_customer_payment_method(
.parse_value("PaymentMethodMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
- "Failed to deserialize metadata to PaymmentmethodMetadata struct",
+ "Failed to deserialize metadata to PaymentmethodMetadata struct",
)?;
for pm_metadata in pm_metadata_vec.payment_method_tokenization {
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 6e4b43593ab..2d8fe43d186 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -147,6 +147,7 @@ pub struct DeleteCardResponse {
}
#[derive(Debug, Deserialize, Serialize)]
+#[serde(transparent)]
pub struct PaymentMethodMetadata {
pub payment_method_tokenization: std::collections::HashMap<String, String>,
}
|
fix
|
add `serde(transparent)` annotation for `PaymentMethodMetadata` (#1899)
|
ac8d81b32b3d91b875113d32782a8c62e39ba2a8
|
2024-01-17 16:31:22
|
Sampras Lopes
|
fix(events): fix event generation for paymentmethods list (#3337)
| false
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index a911d26d865..0eb3d95bfc6 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -23,6 +23,17 @@ postman/ @juspay/hyperswitch-framework
Cargo.toml @juspay/hyperswitch-framework
Cargo.lock @juspay/hyperswitch-framework
+crates/api_models/src/events/ @juspay/hyperswitch-analytics
+crates/api_models/src/events.rs @juspay/hyperswitch-analytics
+crates/api_models/src/analytics/ @juspay/hyperswitch-analytics
+crates/api_models/src/analytics.rs @juspay/hyperswitch-analytics
+crates/router/src/analytics.rs @juspay/hyperswitch-analytics
+crates/router/src/events/ @juspay/hyperswitch-analytics
+crates/router/src/events.rs @juspay/hyperswitch-analytics
+crates/common_utils/src/events/ @juspay/hyperswitch-analytics
+crates/common_utils/src/events.rs @juspay/hyperswitch-analytics
+crates/analytics/ @juspay/hyperswitch-analytics
+
connector-template/ @juspay/hyperswitch-connector
crates/router/src/connector/ @juspay/hyperswitch-connector
crates/router/tests/connectors/ @juspay/hyperswitch-connector
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 43a72b7e392..a8185d2d241 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -39,7 +39,6 @@ impl ApiEventMetric for TimeRange {}
impl_misc_api_event_type!(
PaymentMethodId,
PaymentsSessionResponse,
- PaymentMethodListResponse,
PaymentMethodCreate,
PaymentLinkInitiateRequest,
RetrievePaymentLinkResponse,
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index f718dc1ca4d..32d3dc30bd8 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -3,7 +3,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::{
payment_methods::{
CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest,
- PaymentMethodResponse, PaymentMethodUpdate,
+ PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters,
@@ -119,6 +119,8 @@ impl ApiEventMetric for PaymentMethodListRequest {
}
}
+impl ApiEventMetric for PaymentMethodListResponse {}
+
impl ApiEventMetric for PaymentListFilterConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
|
fix
|
fix event generation for paymentmethods list (#3337)
|
ac7d8c572ce34cb120c9123fd2748ba86049b6f1
|
2024-08-20 14:50:41
|
Sai Harsha Vardhan
|
fix(api-reference): fix api paths for `merchant_connector_account` in api-reference-v2 (#5645)
| false
|
diff --git a/api-reference-v2/api-reference/merchant-connector-account/delete-connector_accounts.mdx b/api-reference-v2/api-reference/merchant-connector-account/delete-connector_accounts.mdx
deleted file mode 100644
index c95826b6917..00000000000
--- a/api-reference-v2/api-reference/merchant-connector-account/delete-connector_accounts.mdx
+++ /dev/null
@@ -1,3 +0,0 @@
----
-openapi: delete /connector_accounts/{id}
----
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/get-connector_accounts.mdx b/api-reference-v2/api-reference/merchant-connector-account/get-connector_accounts.mdx
deleted file mode 100644
index eeae4e44002..00000000000
--- a/api-reference-v2/api-reference/merchant-connector-account/get-connector_accounts.mdx
+++ /dev/null
@@ -1,3 +0,0 @@
----
-openapi: get /connector_accounts/{id}
----
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx
index a6ba2bbef8f..d8cac2bab39 100644
--- a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx
+++ b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /connector_accounts
+openapi: post /v2/connector_accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx
index c95826b6917..5c959648fff 100644
--- a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx
+++ b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx
@@ -1,3 +1,3 @@
---
-openapi: delete /connector_accounts/{id}
+openapi: delete /v2/connector_accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx
index eeae4e44002..918de031276 100644
--- a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx
+++ b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /connector_accounts/{id}
+openapi: get /v2/connector_accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx
index 143d457c8fd..f3cacd3bf50 100644
--- a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx
+++ b/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /connector_accounts/{id}
+openapi: post /v2/connector_accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/post-connector_accounts-1.mdx b/api-reference-v2/api-reference/merchant-connector-account/post-connector_accounts-1.mdx
deleted file mode 100644
index 143d457c8fd..00000000000
--- a/api-reference-v2/api-reference/merchant-connector-account/post-connector_accounts-1.mdx
+++ /dev/null
@@ -1,3 +0,0 @@
----
-openapi: post /connector_accounts/{id}
----
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-connector-account/post-connector_accounts.mdx b/api-reference-v2/api-reference/merchant-connector-account/post-connector_accounts.mdx
deleted file mode 100644
index a6ba2bbef8f..00000000000
--- a/api-reference-v2/api-reference/merchant-connector-account/post-connector_accounts.mdx
+++ /dev/null
@@ -1,3 +0,0 @@
----
-openapi: post /connector_accounts
----
\ No newline at end of file
|
fix
|
fix api paths for `merchant_connector_account` in api-reference-v2 (#5645)
|
c4f9029c8ba3ea2570688e00e551ea979859d3be
|
2023-06-22 12:54:27
|
dependabot[bot]
|
build(deps): bump openssl from 0.10.54 to 0.10.55 (#1503)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 05c45938fd4..422017f9acf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2976,9 +2976,9 @@ checksum = "44d11de466f4a3006fe8a5e7ec84e93b79c70cb992ae0aa0eb631ad2df8abfe2"
[[package]]
name = "openssl"
-version = "0.10.54"
+version = "0.10.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69b3f656a17a6cbc115b5c7a40c616947d213ba182135b014d6051b73ab6f019"
+checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d"
dependencies = [
"bitflags 1.3.2",
"cfg-if",
@@ -3008,9 +3008,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
-version = "0.9.88"
+version = "0.9.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c2ce0f250f34a308dcfdbb351f511359857d4ed2134ba715a4eadd46e1ffd617"
+checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6"
dependencies = [
"cc",
"libc",
|
build
|
bump openssl from 0.10.54 to 0.10.55 (#1503)
|
f8a8d2a0300034c8e6ab36d011f9180993dc5e5f
|
2025-03-18 05:58:15
|
github-actions
|
chore(version): 2025.03.18.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15abfd45725..77e5e47d3ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,35 @@
All notable changes to HyperSwitch will be documented here.
+- - -
+
+## 2025.03.18.0
+
+### Features
+
+- **connector:**
+ - [PAYSTACK] Electronic Fund Transfer(EFT) Payment Flows ([#7440](https://github.com/juspay/hyperswitch/pull/7440)) ([`c39ecda`](https://github.com/juspay/hyperswitch/commit/c39ecda79a9b1df1ccb4e469111e0dfb92a3d82c))
+ - Recurly incoming webhook support ([#7439](https://github.com/juspay/hyperswitch/pull/7439)) ([`2d17dad`](https://github.com/juspay/hyperswitch/commit/2d17dad25d0966fc95f17e0ee91598ea445d4dc9))
+ - [GETNET] Add cards payment flow ([#7256](https://github.com/juspay/hyperswitch/pull/7256)) ([`d346d38`](https://github.com/juspay/hyperswitch/commit/d346d38faf3858ec1e3360fb9e3a2a82e7d330fb))
+ - [Stripebilling] add incoming webhook support ([#7417](https://github.com/juspay/hyperswitch/pull/7417)) ([`3282444`](https://github.com/juspay/hyperswitch/commit/32824441327fce00ecf5dca21bbf48e17910f2df))
+- **payment-link:** Add config for enabling form button only when form is complete ([#7517](https://github.com/juspay/hyperswitch/pull/7517)) ([`0be1f87`](https://github.com/juspay/hyperswitch/commit/0be1f878ed58b18068dccc430d17b612e01e9fe7))
+- Scheme error code and messages in payments api response ([#7528](https://github.com/juspay/hyperswitch/pull/7528)) ([`c702535`](https://github.com/juspay/hyperswitch/commit/c702535e91cb6c489d8c24d1ab0e6be3025d015a))
+
+### Bug Fixes
+
+- **connector:**
+ - [INESPAY] Added iban as required field in Inespay ([#7350](https://github.com/juspay/hyperswitch/pull/7350)) ([`2db2738`](https://github.com/juspay/hyperswitch/commit/2db2738cf8c84704d0765f90cd421f5b5db4b7d8))
+ - Fix incorrect mapping of attempt status in AuthorizeDotNet connector ([#7523](https://github.com/juspay/hyperswitch/pull/7523)) ([`04ede12`](https://github.com/juspay/hyperswitch/commit/04ede122e45a02325b881f8772127ad3d1389895))
+- **connectors:** [Nexixpay] handle optional fields in nexixpay payments requests. ([#7465](https://github.com/juspay/hyperswitch/pull/7465)) ([`fc596ea`](https://github.com/juspay/hyperswitch/commit/fc596eaf1c45cb8ffafca3ad41945134b32b2bb4))
+
+### Refactors
+
+- **currency_conversion:** Add support for expiring forex data in redis ([#7455](https://github.com/juspay/hyperswitch/pull/7455)) ([`480e8c3`](https://github.com/juspay/hyperswitch/commit/480e8c3dcf59d6e4052aa0077dd06278fba973ff))
+- **process_tracker:** Integrate proxy_payments api to process tracker workflow ([#7480](https://github.com/juspay/hyperswitch/pull/7480)) ([`ba3ad87`](https://github.com/juspay/hyperswitch/commit/ba3ad87e06d63910d78fdb217db47064b4d926be))
+
+**Full Changelog:** [`2025.03.17.0...2025.03.18.0`](https://github.com/juspay/hyperswitch/compare/2025.03.17.0...2025.03.18.0)
+
+
- - -
## 2025.03.17.0
|
chore
|
2025.03.18.0
|
bec4f2a24e2236f7814119a6ebf0363cbf598540
|
2024-01-30 16:13:04
|
Kartikeya Hegde
|
fix: empty payment attempts on payment retrieve (#3447)
| false
|
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index b8d71cb32b7..ad52a8aaeab 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -932,12 +932,23 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
}
MerchantStorageScheme::RedisKv => {
let key = format!("mid_{merchant_id}_pid_{payment_id}");
-
- kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key)
- .await
- .change_context(errors::StorageError::KVError)?
- .try_into_scan()
- .change_context(errors::StorageError::KVError)
+ Box::pin(try_redis_get_else_try_database_get(
+ async {
+ kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key)
+ .await?
+ .try_into_scan()
+ },
+ || async {
+ self.router_store
+ .find_attempts_by_merchant_id_payment_id(
+ merchant_id,
+ payment_id,
+ storage_scheme,
+ )
+ .await
+ },
+ ))
+ .await
}
}
}
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index 9339b11a9b9..ad57ad403d4 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -131,7 +131,16 @@ where
}
KvOperation::Scan(pattern) => {
- let result: Vec<T> = redis_conn.hscan_and_deserialize(key, pattern, None).await?;
+ let result: Vec<T> = redis_conn
+ .hscan_and_deserialize(key, pattern, None)
+ .await
+ .and_then(|result| {
+ if result.is_empty() {
+ Err(RedisError::NotFound).into_report()
+ } else {
+ Ok(result)
+ }
+ })?;
Ok(KvResult::Scan(result))
}
|
fix
|
empty payment attempts on payment retrieve (#3447)
|
7d46afd9852a793befa5321835ae9413fafb3fd9
|
2024-06-19 18:02:30
|
Shankar Singh C
|
feat(router): add payment method type duplication check for `google_pay` (#5023)
| false
|
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 54a4e20c89c..64fe526f0c0 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -515,8 +515,10 @@ where
}
},
None => {
- let customer_apple_pay_saved_pm_id_option = if payment_method_type
+ let customer_saved_pm_id_option = if payment_method_type
== Some(api_models::enums::PaymentMethodType::ApplePay)
+ || payment_method_type
+ == Some(api_models::enums::PaymentMethodType::GooglePay)
{
match state
.store
@@ -530,8 +532,7 @@ where
Ok(customer_payment_methods) => Ok(customer_payment_methods
.iter()
.find(|payment_method| {
- payment_method.payment_method_type
- == Some(api_models::enums::PaymentMethodType::ApplePay)
+ payment_method.payment_method_type == payment_method_type
})
.map(|pm| pm.payment_method_id.clone())),
Err(error) => {
@@ -552,10 +553,8 @@ where
Ok(None)
}?;
- if let Some(customer_apple_pay_saved_pm_id) =
- customer_apple_pay_saved_pm_id_option
- {
- resp.payment_method_id = customer_apple_pay_saved_pm_id;
+ if let Some(customer_saved_pm_id) = customer_saved_pm_id_option {
+ resp.payment_method_id = customer_saved_pm_id;
} else {
let pm_metadata =
create_payment_method_metadata(None, connector_token)?;
|
feat
|
add payment method type duplication check for `google_pay` (#5023)
|
d804b2328274189cf5ddab9aac5bee56838618da
|
2023-08-29 11:54:02
|
DEEPANSHU BANSAL
|
feat(connector): [HELCIM] Add template code for Helcim (#2019)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 222e1316078..a46d1670b2c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -173,6 +173,7 @@ fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
+helcim.base_url = "https://api.helcim.com/"
iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
@@ -242,6 +243,7 @@ cards = [
"cybersource",
"globalpay",
"globepay",
+ "helcim",
"mollie",
"paypal",
"shift4",
diff --git a/config/development.toml b/config/development.toml
index 112caeec1c4..23a6a4620ae 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -79,6 +79,7 @@ cards = [
"forte",
"globalpay",
"globepay",
+ "helcim",
"iatapay",
"mollie",
"multisafepay",
@@ -142,6 +143,7 @@ fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
+helcim.base_url = "https://api.helcim.com/"
iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index f7df08b6361..2762cb10095 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -94,6 +94,7 @@ fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
+helcim.base_url = "https://api.helcim.com/"
iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
@@ -152,6 +153,7 @@ cards = [
"forte",
"globalpay",
"globepay",
+ "helcim",
"iatapay",
"mollie",
"multisafepay",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index f9e282531ca..392e8afb67f 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -90,6 +90,7 @@ pub enum Connector {
Forte,
Globalpay,
Globepay,
+ //Helcim, added as template code for future usage,
Iatapay,
Klarna,
Mollie,
@@ -204,6 +205,7 @@ pub enum RoutableConnectors {
Forte,
Globalpay,
Globepay,
+ //Helcim, added as template code for future usage,
Iatapay,
Klarna,
Mollie,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 45bbacfc3cc..cace0fcdcba 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -489,6 +489,7 @@ pub struct Connectors {
pub forte: ConnectorParams,
pub globalpay: ConnectorParams,
pub globepay: ConnectorParams,
+ pub helcim: ConnectorParams,
pub iatapay: ConnectorParams,
pub klarna: ConnectorParams,
pub mollie: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index e6fd352f375..d262702b6d6 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -19,6 +19,7 @@ pub mod fiserv;
pub mod forte;
pub mod globalpay;
pub mod globepay;
+pub mod helcim;
pub mod iatapay;
pub mod klarna;
pub mod mollie;
@@ -54,7 +55,7 @@ pub use self::{
bambora::Bambora, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, globalpay::Globalpay,
- globepay::Globepay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie,
+ globepay::Globepay, helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mollie::Mollie,
multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei,
opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu,
powertranz::Powertranz, rapyd::Rapyd, shift4::Shift4, square::Square, stax::Stax,
diff --git a/crates/router/src/connector/helcim.rs b/crates/router/src/connector/helcim.rs
new file mode 100644
index 00000000000..a6bec7bacd9
--- /dev/null
+++ b/crates/router/src/connector/helcim.rs
@@ -0,0 +1,514 @@
+pub mod transformers;
+
+use std::fmt::Debug;
+
+use error_stack::{IntoReport, ResultExt};
+use masking::ExposeInterface;
+use transformers as helcim;
+
+use crate::{
+ configs::settings,
+ core::errors::{self, CustomResult},
+ headers,
+ services::{
+ self,
+ request::{self, Mask},
+ ConnectorIntegration, ConnectorValidation,
+ },
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response,
+ },
+ utils::{self, BytesExt},
+};
+
+#[derive(Debug, Clone)]
+pub struct Helcim;
+
+impl api::Payment for Helcim {}
+impl api::PaymentSession for Helcim {}
+impl api::ConnectorAccessToken for Helcim {}
+impl api::PreVerify for Helcim {}
+impl api::PaymentAuthorize for Helcim {}
+impl api::PaymentSync for Helcim {}
+impl api::PaymentCapture for Helcim {}
+impl api::PaymentVoid for Helcim {}
+impl api::Refund for Helcim {}
+impl api::RefundExecute for Helcim {}
+impl api::RefundSync for Helcim {}
+impl api::PaymentToken for Helcim {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Helcim
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Helcim
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsAuthorizeType::get_content_type(self)
+ .to_string()
+ .into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Helcim {
+ fn id(&self) -> &'static str {
+ "helcim"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.helcim.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let auth = helcim::HelcimAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: helcim::HelcimErrorResponse = res
+ .response
+ .parse_struct("HelcimErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ })
+ }
+}
+
+impl ConnectorValidation for Helcim {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Helcim
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Helcim
+{
+}
+
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Helcim
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Helcim
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ let req_obj = helcim::HelcimPaymentsRequest::try_from(req)?;
+ let helcim_req = types::RequestBody::log_and_get_request_body(
+ &req_obj,
+ utils::Encode::<helcim::HelcimPaymentsRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(helcim_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ self.validate_capture_method(req.request.capture_method)?;
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: helcim::HelcimPaymentsResponse = res
+ .response
+ .parse_struct("Helcim PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Helcim
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: helcim::HelcimPaymentsResponse = res
+ .response
+ .parse_struct("helcim PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Helcim
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsCaptureType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: helcim::HelcimPaymentsResponse = res
+ .response
+ .parse_struct("Helcim PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Helcim
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Helcim {
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ let req_obj = helcim::HelcimRefundRequest::try_from(req)?;
+ let helcim_req = types::RequestBody::log_and_get_request_body(
+ &req_obj,
+ utils::Encode::<helcim::HelcimRefundRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(helcim_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: helcim::RefundResponse =
+ res.response
+ .parse_struct("helcim RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Helcim {
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .body(types::RefundSyncType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ let response: helcim::RefundResponse = res
+ .response
+ .parse_struct("helcim RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Helcim {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+}
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs
new file mode 100644
index 00000000000..20a8bef08a2
--- /dev/null
+++ b/crates/router/src/connector/helcim/transformers.rs
@@ -0,0 +1,205 @@
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::PaymentsAuthorizeRequestData,
+ core::errors,
+ types::{self, api, storage::enums},
+};
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct HelcimPaymentsRequest {
+ amount: i64,
+ card: HelcimCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct HelcimCard {
+ name: Secret<String>,
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for HelcimPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data.clone() {
+ api::PaymentMethodData::Card(req_card) => {
+ let card = HelcimCard {
+ name: req_card.card_holder_name,
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.request.amount,
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct HelcimAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for HelcimAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum HelcimPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<HelcimPaymentStatus> for enums::AttemptStatus {
+ fn from(item: HelcimPaymentStatus) -> Self {
+ match item {
+ HelcimPaymentStatus::Succeeded => Self::Charged,
+ HelcimPaymentStatus::Failed => Self::Failure,
+ HelcimPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct HelcimPaymentsResponse {
+ status: HelcimPaymentStatus,
+ id: String,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, HelcimPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, HelcimPaymentsResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.status),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct HelcimRefundRequest {
+ pub amount: i64,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for HelcimRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.request.refund_amount,
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct HelcimErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 0b03061841e..5782887b9ad 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -151,6 +151,7 @@ default_imp_for_complete_authorize!(
connector::Fiserv,
connector::Forte,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Multisafepay,
@@ -220,6 +221,7 @@ default_imp_for_create_customer!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -289,6 +291,7 @@ default_imp_for_connector_redirect_response!(
connector::Fiserv,
connector::Forte,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Multisafepay,
@@ -341,6 +344,7 @@ default_imp_for_connector_request_id!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -417,6 +421,7 @@ default_imp_for_accept_dispute!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -513,6 +518,7 @@ default_imp_for_file_upload!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -586,6 +592,7 @@ default_imp_for_submit_evidence!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -659,6 +666,7 @@ default_imp_for_defend_dispute!(
connector::Globepay,
connector::Forte,
connector::Globalpay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -735,6 +743,7 @@ default_imp_for_pre_processing_steps!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
@@ -789,6 +798,7 @@ default_imp_for_payouts!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -863,6 +873,7 @@ default_imp_for_payouts_create!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -940,6 +951,7 @@ default_imp_for_payouts_eligibility!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -1014,6 +1026,7 @@ default_imp_for_payouts_fulfill!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -1088,6 +1101,7 @@ default_imp_for_payouts_cancel!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -1163,6 +1177,7 @@ default_imp_for_payouts_quote!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
@@ -1238,6 +1253,7 @@ default_imp_for_payouts_recipient!(
connector::Forte,
connector::Globalpay,
connector::Globepay,
+ connector::Helcim,
connector::Iatapay,
connector::Klarna,
connector::Mollie,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 283aae98352..546bc3efe67 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -305,6 +305,7 @@ impl ConnectorData {
enums::Connector::Forte => Ok(Box::new(&connector::Forte)),
enums::Connector::Globalpay => Ok(Box::new(&connector::Globalpay)),
enums::Connector::Globepay => Ok(Box::new(&connector::Globepay)),
+ //enums::Connector::Helcim => Ok(Box::new(&connector::Helcim)), , it is added as template code for future usage
enums::Connector::Iatapay => Ok(Box::new(&connector::Iatapay)),
enums::Connector::Klarna => Ok(Box::new(&connector::Klarna)),
enums::Connector::Mollie => Ok(Box::new(&connector::Mollie)),
diff --git a/crates/router/tests/connectors/helcim.rs b/crates/router/tests/connectors/helcim.rs
new file mode 100644
index 00000000000..f8eb9635666
--- /dev/null
+++ b/crates/router/tests/connectors/helcim.rs
@@ -0,0 +1,419 @@
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct HelcimTest;
+impl ConnectorActions for HelcimTest {}
+impl utils::Connector for HelcimTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Helcim;
+ types::api::ConnectorData {
+ connector: Box::new(&Helcim),
+ connector_name: types::Connector::DummyConnector1,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .helcim
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "helcim".to_string()
+ }
+}
+
+static CONNECTOR: HelcimTest = HelcimTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenerios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index bbb1b14bd13..360636ac67b 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -26,6 +26,7 @@ mod fiserv;
mod forte;
mod globalpay;
mod globepay;
+mod helcim;
mod iatapay;
mod mollie;
mod multisafepay;
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 981d5b4a5c7..aeca3d49779 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -171,3 +171,6 @@ key1 = "transaction key"
[square]
api_key="API Key"
+
+[helcim]
+api_key="API Key"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 3a6d2c7d376..fbbd5d1c40a 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -32,6 +32,7 @@ pub struct ConnectorAuthentication {
pub forte: Option<MultiAuthKey>,
pub globalpay: Option<BodyKey>,
pub globepay: Option<BodyKey>,
+ pub helcim: Option<HeaderKey>,
pub iatapay: Option<SignatureKey>,
pub mollie: Option<BodyKey>,
pub multisafepay: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 40010ae889b..ffc12a5df81 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -80,6 +80,7 @@ fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
+helcim.base_url = "https://api.helcim.com/"
iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
@@ -137,6 +138,7 @@ cards = [
"forte",
"globalpay",
"globepay",
+ "helcim",
"iatapay",
"mollie",
"multisafepay",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 4302e535ce0..cded02e851c 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu powertranz rapyd shift4 square stax stripe trustpay tsys wise worldline worldpay "$1")
+ connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu powertranz rapyd shift4 square stax stripe trustpay tsys wise worldline worldpay "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
feat
|
[HELCIM] Add template code for Helcim (#2019)
|
ea219dc8939c52493216f439110d828252e7a3cf
|
2022-12-12 12:46:04
|
Nishant Joshi
|
feat(async_refund): add sync feature to async refund (#93)
| false
|
diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs
index cdeb26113b9..516c0ee005b 100644
--- a/crates/router/src/compatibility/stripe/refunds.rs
+++ b/crates/router/src/compatibility/stripe/refunds.rs
@@ -60,7 +60,12 @@ pub(crate) async fn refund_retrieve(
&req,
refund_id,
|state, merchant_account, refund_id| {
- refunds::refund_retrieve_core(state, merchant_account, refund_id)
+ refunds::refund_response_wrapper(
+ state,
+ merchant_account,
+ refund_id,
+ refunds::refund_retrieve_core,
+ )
},
api::MerchantAuthentication::ApiKey,
)
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 96e44e5c639..6b5f79a5376 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -356,6 +356,8 @@ pub enum ProcessTrackerError {
FlowExecutionError { flow: String },
#[error("Not Implemented")]
NotImplemented,
+ #[error("Job not found")]
+ JobNotFound,
#[error("Recieved Error ApiResponseError: {0}")]
EApiErrorResponse(error_stack::Report<ApiErrorResponse>),
#[error("Recieved Error StorageError: {0}")]
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index c58e1f0cfc3..fc2e4937ada 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -9,9 +9,9 @@ use crate::{
errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},
payments, utils as core_utils,
},
- db::StorageInterface,
- logger,
+ db, logger,
routes::AppState,
+ scheduler::{process_data, utils as process_tracker_utils, workflows::payment_sync},
services,
types::{
self,
@@ -163,12 +163,28 @@ pub async fn trigger_refund_to_gateway(
// ********************************************** REFUND SYNC **********************************************
+pub async fn refund_response_wrapper<'a, F, Fut, T>(
+ state: &'a AppState,
+ merchant_account: storage::MerchantAccount,
+ refund_id: String,
+ f: F,
+) -> RouterResponse<refunds::RefundResponse>
+where
+ F: Fn(&'a AppState, storage::MerchantAccount, String) -> Fut,
+ Fut: futures::Future<Output = RouterResult<T>>,
+ refunds::RefundResponse: From<T>,
+{
+ Ok(services::BachResponse::Json(
+ f(state, merchant_account, refund_id).await?.into(),
+ ))
+}
+
#[instrument(skip_all)]
pub async fn refund_retrieve_core(
state: &AppState,
merchant_account: storage::MerchantAccount,
refund_id: String,
-) -> RouterResponse<refunds::RefundResponse> {
+) -> RouterResult<storage::Refund> {
let db = &*state.store;
let (merchant_id, payment_intent, payment_attempt, refund, response);
@@ -212,7 +228,7 @@ pub async fn refund_retrieve_core(
)
.await?;
- Ok(services::BachResponse::Json(response.into()))
+ Ok(response)
}
#[instrument(skip_all)]
@@ -286,7 +302,7 @@ pub async fn sync_refund_with_gateway(
// ********************************************** REFUND UPDATE **********************************************
pub async fn refund_update_core(
- db: &dyn StorageInterface,
+ db: &dyn db::StorageInterface,
merchant_account: storage::MerchantAccount,
refund_id: &str,
req: refunds::RefundRequest,
@@ -576,9 +592,9 @@ pub async fn schedule_refund_execution(
#[instrument(skip_all)]
pub async fn sync_refund_with_gateway_workflow(
- db: &dyn StorageInterface,
+ state: &AppState,
refund_tracker: &storage::ProcessTracker,
-) -> RouterResult<()> {
+) -> Result<(), errors::ProcessTrackerError> {
let refund_core =
serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone())
.into_report()
@@ -590,7 +606,8 @@ pub async fn sync_refund_with_gateway_workflow(
)
})?;
- let merchant_account = db
+ let merchant_account = state
+ .store
.find_merchant_account_by_merchant_id(&refund_core.merchant_id)
.await
.map_err(|error| {
@@ -598,7 +615,8 @@ pub async fn sync_refund_with_gateway_workflow(
})?;
// FIXME we actually don't use this?
- let _refund = db
+ let _refund = state
+ .store
.find_refund_by_internal_reference_id_merchant_id(
&refund_core.refund_internal_reference_id,
&refund_core.merchant_id,
@@ -607,22 +625,53 @@ pub async fn sync_refund_with_gateway_workflow(
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?;
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(&refund_core.merchant_id)
+ .await?;
+
+ let response = refund_retrieve_core(
+ state,
+ merchant_account,
+ refund_core.refund_internal_reference_id,
+ )
+ .await?;
+ let terminal_status = vec![
+ enums::RefundStatus::Success,
+ enums::RefundStatus::Failure,
+ enums::RefundStatus::TransactionFailure,
+ ];
+ match response.refund_status {
+ status if terminal_status.contains(&status) => {
+ let id = refund_tracker.id.clone();
+ refund_tracker
+ .clone()
+ .finish_with_status(&*state.store, format!("COMPLETED_BY_PT_{}", id))
+ .await?
+ }
+ _ => {
+ payment_sync::retry_sync_task(
+ &*state.store,
+ response.connector,
+ response.merchant_id,
+ refund_tracker.to_owned(),
+ )
+ .await?
+ }
+ }
+
Ok(())
- // sync_refund_with_gateway(data, &refund).await.map(|_| ())
}
#[instrument(skip_all)]
pub async fn start_refund_workflow(
state: &AppState,
refund_tracker: &storage::ProcessTracker,
-) -> RouterResult<()> {
+) -> Result<(), errors::ProcessTrackerError> {
match refund_tracker.name.as_deref() {
Some("EXECUTE_REFUND") => trigger_refund_execute_workflow(state, refund_tracker).await,
- Some("SYNC_REFUND") => {
- sync_refund_with_gateway_workflow(&*state.store, refund_tracker).await
- }
- _ => Err(report!(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Job name cannot be identified")),
+ Some("SYNC_REFUND") => sync_refund_with_gateway_workflow(state, refund_tracker).await,
+ _ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
@@ -630,7 +679,7 @@ pub async fn start_refund_workflow(
pub async fn trigger_refund_execute_workflow(
state: &AppState,
refund_tracker: &storage::ProcessTracker,
-) -> RouterResult<()> {
+) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let refund_core =
serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone())
@@ -703,11 +752,16 @@ pub async fn trigger_refund_execute_workflow(
add_refund_sync_task(db, &updated_refund, "REFUND_WORKFLOW_ROUTER").await?;
}
(true, enums::RefundStatus::Pending) => {
- //create sync task
+ // create sync task
add_refund_sync_task(db, &refund, "REFUND_WORKFLOW_ROUTER").await?;
}
(_, _) => {
//mark task as finished
+ let id = refund_tracker.id.clone();
+ refund_tracker
+ .clone()
+ .finish_with_status(db, format!("COMPLETED_BY_PT_{}", id))
+ .await?;
}
};
Ok(())
@@ -727,7 +781,7 @@ pub fn refund_to_refund_core_workflow_model(
#[instrument(skip_all)]
pub async fn add_refund_sync_task(
- db: &dyn StorageInterface,
+ db: &dyn db::StorageInterface,
refund: &storage::Refund,
runner: &str,
) -> RouterResult<storage::ProcessTracker> {
@@ -762,7 +816,7 @@ pub async fn add_refund_sync_task(
#[instrument(skip_all)]
pub async fn add_refund_execute_task(
- db: &dyn StorageInterface,
+ db: &dyn db::StorageInterface,
refund: &storage::Refund,
runner: &str,
) -> RouterResult<storage::ProcessTracker> {
@@ -794,3 +848,49 @@ pub async fn add_refund_execute_task(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(response)
}
+
+pub async fn get_refund_sync_process_schedule_time(
+ db: &dyn db::StorageInterface,
+ connector: &str,
+ merchant_id: &str,
+ retry_count: i32,
+) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
+ let redis_mapping: errors::CustomResult<process_data::ConnectorPTMapping, errors::RedisError> =
+ db::get_and_deserialize_key(
+ db,
+ &format!("pt_mapping_refund_sync_{}", connector),
+ "ConnectorPTMapping",
+ )
+ .await;
+
+ let mapping = match redis_mapping {
+ Ok(x) => x,
+ Err(err) => {
+ logger::error!("Error: while getting connector mapping: {}", err);
+ process_data::ConnectorPTMapping::default()
+ }
+ };
+
+ let time_delta =
+ process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count + 1);
+
+ Ok(process_tracker_utils::get_time_from_delta(time_delta))
+}
+
+pub async fn retry_refund_sync_task(
+ db: &dyn db::StorageInterface,
+ connector: String,
+ merchant_id: String,
+ pt: storage::ProcessTracker,
+) -> Result<(), errors::ProcessTrackerError> {
+ let schedule_time =
+ get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?;
+
+ match schedule_time {
+ Some(s_time) => pt.retry(db, s_time).await,
+ None => {
+ pt.finish_with_status(db, "RETRIES_EXCEEDED".to_string())
+ .await
+ }
+ }
+}
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index cc19b35242b..bbc26431c08 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -42,7 +42,7 @@ pub async fn refunds_retrieve(
&req,
refund_id,
|state, merchant_account, refund_id| {
- refund_retrieve_core(state, merchant_account, refund_id)
+ refund_response_wrapper(state, merchant_account, refund_id, refund_retrieve_core)
},
api::MerchantAuthentication::ApiKey,
)
diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs
index 8b701163353..2d94752e432 100644
--- a/crates/router/src/scheduler/utils.rs
+++ b/crates/router/src/scheduler/utils.rs
@@ -8,7 +8,7 @@ use redis_interface::{RedisConnectionPool, RedisEntryId};
use router_env::opentelemetry;
use uuid::Uuid;
-use super::{consumer, metrics, workflows};
+use super::{consumer, metrics, process_data, workflows};
use crate::{
configs::settings::SchedulerSettings,
core::errors::{self, CustomResult},
@@ -266,3 +266,40 @@ pub fn add_histogram_metrics(
);
};
}
+
+pub fn get_schedule_time(
+ mapping: process_data::ConnectorPTMapping,
+ merchant_name: &str,
+ retry_count: i32,
+) -> Option<i32> {
+ let mapping = match mapping.custom_merchant_mapping.get(merchant_name) {
+ Some(map) => map.clone(),
+ None => mapping.default_mapping,
+ };
+
+ if retry_count == 0 {
+ Some(mapping.start_after)
+ } else {
+ get_delay(
+ retry_count,
+ mapping.count.iter().zip(mapping.frequency.iter()),
+ )
+ }
+}
+
+fn get_delay<'a>(
+ retry_count: i32,
+ mut array: impl Iterator<Item = (&'a i32, &'a i32)>,
+) -> Option<i32> {
+ match array.next() {
+ Some(ele) => {
+ let v = retry_count - ele.0;
+ if v <= 0 {
+ Some(*ele.1)
+ } else {
+ get_delay(v, array)
+ }
+ }
+ None => None,
+ }
+}
diff --git a/crates/router/src/scheduler/workflows/payment_sync.rs b/crates/router/src/scheduler/workflows/payment_sync.rs
index 5306d7b426e..6566e40bb07 100644
--- a/crates/router/src/scheduler/workflows/payment_sync.rs
+++ b/crates/router/src/scheduler/workflows/payment_sync.rs
@@ -1,10 +1,12 @@
+use router_env::logger;
+
use super::{PaymentsSyncWorkflow, ProcessTrackerWorkflow};
use crate::{
core::payments::{self as payment_flows, operations},
db::{get_and_deserialize_key, StorageInterface},
errors,
routes::AppState,
- scheduler::{consumer, process_data},
+ scheduler::{consumer, process_data, utils},
types::{
api,
storage::{self, enums},
@@ -102,48 +104,14 @@ pub async fn get_sync_process_schedule_time(
.await;
let mapping = match redis_mapping {
Ok(x) => x,
- Err(_) => process_data::ConnectorPTMapping::default(),
- };
- let time_delta = get_sync_schedule_time(mapping, merchant_id, retry_count + 1);
-
- Ok(crate::scheduler::utils::get_time_from_delta(time_delta))
-}
-
-pub fn get_sync_schedule_time(
- mapping: process_data::ConnectorPTMapping,
- merchant_name: &str,
- retry_count: i32,
-) -> Option<i32> {
- let mapping = match mapping.custom_merchant_mapping.get(merchant_name) {
- Some(map) => map.clone(),
- None => mapping.default_mapping,
+ Err(err) => {
+ logger::error!("Redis Mapping Error: {}", err);
+ process_data::ConnectorPTMapping::default()
+ }
};
+ let time_delta = utils::get_schedule_time(mapping, merchant_id, retry_count + 1);
- if retry_count == 0 {
- Some(mapping.start_after)
- } else {
- get_delay(
- retry_count,
- mapping.count.iter().zip(mapping.frequency.iter()),
- )
- }
-}
-
-fn get_delay<'a>(
- retry_count: i32,
- mut array: impl Iterator<Item = (&'a i32, &'a i32)>,
-) -> Option<i32> {
- match array.next() {
- Some(ele) => {
- let v = retry_count - ele.0;
- if v <= 0 {
- Some(*ele.1)
- } else {
- get_delay(v, array)
- }
- }
- None => None,
- }
+ Ok(utils::get_time_from_delta(time_delta))
}
pub async fn retry_sync_task(
@@ -172,9 +140,9 @@ mod tests {
#[test]
fn test_get_default_schedule_time() {
let schedule_time_delta =
- get_sync_schedule_time(process_data::ConnectorPTMapping::default(), "-", 0).unwrap();
+ utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 0).unwrap();
let first_retry_time_delta =
- get_sync_schedule_time(process_data::ConnectorPTMapping::default(), "-", 1).unwrap();
+ utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 1).unwrap();
let cpt_default = process_data::ConnectorPTMapping::default().default_mapping;
assert_eq!(
vec![schedule_time_delta, first_retry_time_delta],
|
feat
|
add sync feature to async refund (#93)
|
cebe993660c1afbbd0c442c0811f215286ccff8d
|
2023-07-04 13:10:03
|
Hrithikesh
|
fix: add appropriate printable text for Result returned from delete_tokenized_data() (#1369)
| false
|
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 3ef6e89e055..50eee658b37 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -448,10 +448,10 @@ impl Vault {
if resp == "Ok" {
logger::info!("Card From locker deleted Successfully")
} else {
- logger::error!("Error: Deleting Card From Locker : {}", resp)
+ logger::error!("Error: Deleting Card From Locker : {:?}", resp)
}
}
- Err(err) => logger::error!("Err: Deleting Card From Locker : {}", err),
+ Err(err) => logger::error!("Err: Deleting Card From Locker : {:?}", err),
}
}
}
@@ -655,7 +655,9 @@ pub async fn delete_tokenized_data(
service_name: VAULT_SERVICE_NAME.to_string(),
};
let payload = serde_json::to_string(&payload_to_be_encrypted)
- .map_err(|_x| errors::ApiErrorResponse::InternalServerError)?;
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error serializing api::DeleteTokenizeByTokenRequest")?;
let (public_key, _private_key) = get_locker_jwe_keys(&state.kms_secrets)
.await
@@ -679,7 +681,8 @@ pub async fn delete_tokenized_data(
.attach_printable("Making Delete Tokenized request failed")?;
let response = services::call_connector_api(state, request)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while making /tokenize/delete/token call to the locker")?;
match response {
Ok(r) => {
let delete_response = std::str::from_utf8(&r.response)
@@ -771,14 +774,14 @@ pub async fn start_tokenize_data_workflow(
.finish_with_status(db, format!("COMPLETED_BY_PT_{id}"))
.await?;
} else {
- logger::error!("Error: Deleting Card From Locker : {}", resp);
+ logger::error!("Error: Deleting Card From Locker : {:?}", resp);
retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned())
.await?;
scheduler_metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
}
}
Err(err) => {
- logger::error!("Err: Deleting Card From Locker : {}", err);
+ logger::error!("Err: Deleting Card From Locker : {:?}", err);
retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned())
.await?;
scheduler_metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]);
|
fix
|
add appropriate printable text for Result returned from delete_tokenized_data() (#1369)
|
4a0afb8213cce47cabe9e3f5d22ad1dccb02c20f
|
2024-10-24 18:45:21
|
Mani Chandra
|
feat(authz): Create a permission generator (#6394)
| false
|
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index e64639646d1..19027c3cbf8 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,23 +1,9 @@
-use common_enums::PermissionGroup;
+use common_enums::{ParentGroup, PermissionGroup};
use common_utils::pii;
use masking::Secret;
pub mod role;
-#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)]
-pub enum ParentGroup {
- Operations,
- Connectors,
- Workflows,
- Analytics,
- Users,
- #[serde(rename = "MerchantAccess")]
- Merchant,
- #[serde(rename = "OrganizationAccess")]
- Organization,
- Recon,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3ce9d079c63..c103153eec8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2890,6 +2890,47 @@ pub enum PermissionGroup {
ReconOps,
}
+#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)]
+pub enum ParentGroup {
+ Operations,
+ Connectors,
+ Workflows,
+ Analytics,
+ Users,
+ #[serde(rename = "MerchantAccess")]
+ Merchant,
+ #[serde(rename = "OrganizationAccess")]
+ Organization,
+ Recon,
+}
+
+#[derive(Clone, Copy, Eq, PartialEq, Hash)]
+pub enum Resource {
+ Payment,
+ Refund,
+ ApiKey,
+ Account,
+ Connector,
+ Routing,
+ Dispute,
+ Mandate,
+ Customer,
+ Analytics,
+ ThreeDsDecisionManager,
+ SurchargeDecisionManager,
+ User,
+ WebhookEvent,
+ Payout,
+ Report,
+ Recon,
+}
+
+#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
+pub enum PermissionScope {
+ Read,
+ Write,
+}
+
/// Name of banks supported by Hyperswitch
#[derive(
Clone,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index aa6db56bb34..150931e9c8a 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -402,8 +402,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -441,8 +440,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -487,8 +485,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -528,8 +525,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -567,8 +563,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -613,8 +608,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -654,8 +648,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -693,8 +686,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -739,8 +731,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -774,8 +765,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -813,8 +803,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -853,8 +842,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -893,8 +881,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -924,8 +911,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -953,8 +939,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -989,8 +974,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1018,8 +1002,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1049,8 +1032,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1078,8 +1060,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1114,8 +1095,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1139,8 +1119,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1168,8 +1147,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1201,8 +1179,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1235,8 +1212,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1267,8 +1243,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1318,8 +1293,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1367,8 +1341,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1423,8 +1396,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1474,8 +1446,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1523,8 +1494,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1579,8 +1549,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1630,8 +1599,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1679,8 +1647,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1734,8 +1701,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1773,8 +1739,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1798,8 +1763,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1830,8 +1794,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1948,8 +1911,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2065,8 +2027,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2096,8 +2057,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2132,8 +2092,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2161,8 +2120,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2202,8 +2160,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2248,8 +2205,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2287,8 +2243,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2319,8 +2274,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2349,8 +2303,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2386,8 +2339,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 1d188168e5c..284be4ab4ba 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -16,14 +16,14 @@ use crate::{
routes::{app::ReqState, SessionState},
services::{
authentication as auth,
- authorization::{info, roles},
+ authorization::{info, permission_groups::PermissionGroupExt, roles},
ApplicationResponse,
},
types::domain,
utils,
};
pub mod role;
-use common_enums::{EntityType, PermissionGroup};
+use common_enums::{EntityType, ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
@@ -44,11 +44,10 @@ pub async fn get_authorization_info_with_group_tag(
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| {
PermissionGroup::iter()
- .map(|value| (info::get_parent_name(value), value))
+ .map(|group| (group.parent(), group))
.fold(
HashMap::new(),
- |mut acc: HashMap<user_role_api::ParentGroup, Vec<PermissionGroup>>,
- (key, value)| {
+ |mut acc: HashMap<ParentGroup, Vec<PermissionGroup>>, (key, value)| {
acc.entry(key).or_default().push(value);
acc
},
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 78238d3af07..b197101d65f 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -52,8 +51,7 @@ pub async fn organization_update(
&auth::AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
- required_permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Organization,
+ required_permission: Permission::OrganizationAccountWrite,
},
req.headers(),
),
@@ -85,8 +83,7 @@ pub async fn organization_retrieve(
&auth::AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
- required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Organization,
+ required_permission: Permission::OrganizationAccountRead,
},
req.headers(),
),
@@ -139,8 +136,11 @@ pub async fn retrieve_merchant_account(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Profile,
+ // This should ideally be MerchantAccountRead, but since FE is calling this API for
+ // profile level users currently keeping this as ProfileAccountRead. FE is removing
+ // this API call for profile level users.
+ // TODO: Convert this to MerchantAccountRead once FE changes are done.
+ required_permission: Permission::ProfileAccountRead,
},
req.headers(),
),
@@ -172,7 +172,6 @@ pub async fn merchant_account_list(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -200,7 +199,6 @@ pub async fn merchant_account_list(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -232,7 +230,6 @@ pub async fn update_merchant_account(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -298,8 +295,7 @@ pub async fn connector_create(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
@@ -336,8 +332,7 @@ pub async fn connector_create(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
@@ -399,8 +394,7 @@ pub async fn connector_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
@@ -438,8 +432,7 @@ pub async fn connector_retrieve(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
@@ -469,8 +462,7 @@ pub async fn connector_list(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
@@ -517,8 +509,7 @@ pub async fn connector_list(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
@@ -569,8 +560,7 @@ pub async fn connector_list_profile(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
@@ -631,8 +621,7 @@ pub async fn connector_update(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
@@ -683,8 +672,7 @@ pub async fn connector_update(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
@@ -739,8 +727,7 @@ pub async fn connector_delete(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
@@ -778,8 +765,7 @@ pub async fn connector_delete(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index bbecaae9e80..1a2f60bcccb 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, Responder};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -33,8 +32,7 @@ pub async fn api_key_create(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -64,8 +62,7 @@ pub async fn api_key_create(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -99,8 +96,7 @@ pub async fn api_key_retrieve(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -132,8 +128,7 @@ pub async fn api_key_retrieve(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -169,8 +164,7 @@ pub async fn api_key_update(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -203,8 +197,7 @@ pub async fn api_key_update(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -236,8 +229,7 @@ pub async fn api_key_revoke(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -269,8 +261,7 @@ pub async fn api_key_revoke(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -305,8 +296,7 @@ pub async fn api_key_list(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -336,8 +326,7 @@ pub async fn api_key_list(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index 4738df5ed2c..f54f61d8a00 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
-use common_enums::EntityType;
use router_env::Flow;
use crate::{
@@ -39,7 +38,6 @@ pub async fn add_entry_to_blocklist(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -78,7 +76,6 @@ pub async fn remove_entry_from_blocklist(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -119,7 +116,6 @@ pub async fn list_blocked_payment_methods(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -160,7 +156,6 @@ pub async fn toggle_blocklist_guard(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs
index f7494e182c1..8ecd321df94 100644
--- a/crates/router/src/routes/connector_onboarding.rs
+++ b/crates/router/src/routes/connector_onboarding.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::connector_onboarding as api_types;
-use common_enums::EntityType;
use router_env::Flow;
use super::AppState;
@@ -24,7 +23,6 @@ pub async fn get_action_url(
core::get_action_url,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -46,7 +44,6 @@ pub async fn sync_onboarding_status(
core::sync_onboarding_status,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -68,7 +65,6 @@ pub async fn reset_tracking_id(
core::reset_tracking_id,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 536bca10f3d..5ff155966a0 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse, Responder};
-use common_enums::EntityType;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::id_type;
use router_env::{instrument, tracing, Flow};
@@ -29,8 +28,7 @@ pub async fn customers_create(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -55,8 +53,7 @@ pub async fn customers_retrieve(
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth {
- permission: Permission::CustomerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerRead,
})
} else {
match auth::is_ephemeral_auth(req.headers()) {
@@ -98,8 +95,7 @@ pub async fn customers_retrieve(
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth {
- permission: Permission::CustomerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerRead,
})
} else {
match auth::is_ephemeral_auth(req.headers()) {
@@ -148,8 +144,7 @@ pub async fn customers_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
@@ -187,8 +182,7 @@ pub async fn customers_update(
auth::auth_type(
&auth::ApiKeyAuth,
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -225,8 +219,7 @@ pub async fn customers_update(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -256,8 +249,7 @@ pub async fn customers_delete(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -290,8 +282,7 @@ pub async fn customers_delete(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -328,8 +319,7 @@ pub async fn get_customer_mandates(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MandateRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantMandateRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 22c1e3f1988..5577bb96ef0 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -1,7 +1,6 @@
use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::disputes as dispute_models;
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use crate::{core::api_locking, services::authorization::permissions::Permission};
@@ -50,8 +49,7 @@ pub async fn retrieve_dispute(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -102,8 +100,7 @@ pub async fn retrieve_disputes_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
@@ -160,8 +157,7 @@ pub async fn retrieve_disputes_list_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -195,8 +191,7 @@ pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest)
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
@@ -237,8 +232,7 @@ pub async fn get_disputes_filters_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -289,8 +283,7 @@ pub async fn accept_dispute(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -335,8 +328,7 @@ pub async fn submit_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -389,8 +381,7 @@ pub async fn attach_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -435,8 +426,7 @@ pub async fn retrieve_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -478,8 +468,7 @@ pub async fn delete_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -508,8 +497,7 @@ pub async fn get_disputes_aggregate(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
@@ -543,8 +531,7 @@ pub async fn get_disputes_aggregate_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index c0ccbfa9f8f..cb832d81a16 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -117,8 +116,7 @@ pub async fn retrieve_mandates_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MandateRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantMandateRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 8d95ee64ad0..0dbddbef77b 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -4,7 +4,6 @@
))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use common_utils::{errors::CustomResult, id_type};
use diesel_models::enums::IntentStatus;
use error_stack::ResultExt;
@@ -881,15 +880,13 @@ pub async fn list_countries_currencies_for_connector_payment_method(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index f13a873473a..bca7bd37ccc 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -5,7 +5,6 @@ use crate::{
pub mod helpers;
use actix_web::{web, Responder};
-use common_enums::EntityType;
use error_stack::report;
use hyperswitch_domain_models::payments::HeaderPayload;
use masking::PeekInterface;
@@ -93,8 +92,7 @@ pub async fn payments_create(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
@@ -148,8 +146,7 @@ pub async fn payments_create_intent(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
@@ -285,8 +282,7 @@ pub async fn payments_retrieve(
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
@@ -995,8 +991,7 @@ pub async fn payments_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
req.headers(),
),
@@ -1031,8 +1026,7 @@ pub async fn profile_payments_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
@@ -1065,8 +1059,7 @@ pub async fn payments_list_by_filter(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1097,8 +1090,7 @@ pub async fn profile_payments_list_by_filter(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1123,8 +1115,7 @@ pub async fn get_filters_for_payments(
payments::get_filters_for_payments(state, auth.merchant_account, auth.key_store, req)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1147,8 +1138,7 @@ pub async fn get_payment_filters(
payments::get_payment_filters(state, auth.merchant_account, None)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1175,8 +1165,7 @@ pub async fn get_payment_filters_profile(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1201,8 +1190,7 @@ pub async fn get_payments_aggregates(
payments::get_aggregates_for_payments(state, auth.merchant_account, None, req)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1262,8 +1250,7 @@ pub async fn payments_approve(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
@@ -1327,8 +1314,7 @@ pub async fn payments_reject(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
@@ -1970,8 +1956,7 @@ pub async fn get_payments_aggregates_profile(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index ad860195a2a..62d16c4c4d5 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -3,7 +3,6 @@ use actix_web::{
http::header::HeaderMap,
web, HttpRequest, HttpResponse, Responder,
};
-use common_enums::EntityType;
use common_utils::consts;
use router_env::{instrument, tracing, Flow};
@@ -84,8 +83,7 @@ pub async fn payouts_retrieve(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
@@ -237,8 +235,7 @@ pub async fn payouts_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
@@ -277,8 +274,7 @@ pub async fn payouts_list_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
@@ -317,8 +313,7 @@ pub async fn payouts_list_by_filter(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
@@ -357,8 +352,7 @@ pub async fn payouts_list_by_filter_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
@@ -390,8 +384,7 @@ pub async fn payouts_list_available_filters_for_merchant(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
@@ -429,8 +422,7 @@ pub async fn payouts_list_available_filters_for_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs
index f2dc322af17..cbb7957987f 100644
--- a/crates/router/src/routes/profiles.rs
+++ b/crates/router/src/routes/profiles.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -34,7 +33,6 @@ pub async fn profile_create(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -65,7 +63,6 @@ pub async fn profile_create(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -97,8 +94,7 @@ pub async fn profile_retrieve(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileAccountRead,
},
req.headers(),
),
@@ -127,7 +123,6 @@ pub async fn profile_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -161,8 +156,7 @@ pub async fn profile_update(
&auth::JWTAuthMerchantAndProfileFromRoute {
merchant_id: merchant_id.clone(),
profile_id: profile_id.clone(),
- required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileAccountWrite,
},
req.headers(),
),
@@ -192,7 +186,6 @@ pub async fn profile_update(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -244,7 +237,6 @@ pub async fn profiles_list(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -278,8 +270,7 @@ pub async fn profiles_list_at_profile_level(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileAccountRead,
},
req.headers(),
),
@@ -312,8 +303,7 @@ pub async fn toggle_connector_agnostic_mit(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: permissions::Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: permissions::Permission::MerchantRoutingWrite,
},
req.headers(),
),
@@ -372,8 +362,7 @@ pub async fn payment_connector_list_profile(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: permissions::Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileConnectorRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs
index 1ec571ff7c9..cdc2ae758e9 100644
--- a/crates/router/src/routes/recon.rs
+++ b/crates/router/src/routes/recon.rs
@@ -1,5 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use api_models::{enums::EntityType, recon as recon_api};
+use api_models::recon as recon_api;
use router_env::Flow;
use super::AppState;
@@ -38,8 +38,7 @@ pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest
(),
|state, user, _, _| recon::send_recon_request(state, user),
&authentication::JWTAuth {
- permission: Permission::ReconAdmin,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReconWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -55,8 +54,7 @@ pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> Ht
(),
|state, user, _, _| recon::generate_recon_token(state, user),
&authentication::JWTAuth {
- permission: Permission::ReconAdmin,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReconWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index c76ee600efe..cbcfbcdcbf1 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -49,8 +48,7 @@ pub async fn refunds_create(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundWrite,
},
req.headers(),
),
@@ -113,8 +111,7 @@ pub async fn refunds_retrieve(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
@@ -245,8 +242,7 @@ pub async fn refunds_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -293,8 +289,7 @@ pub async fn refunds_list_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
@@ -336,8 +331,7 @@ pub async fn refunds_filter_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -374,8 +368,7 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -419,8 +412,7 @@ pub async fn get_refunds_filters_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
@@ -449,8 +441,7 @@ pub async fn get_refunds_aggregates(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -507,8 +498,7 @@ pub async fn get_refunds_aggregate_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 4c8d89fa87d..3e0355a884a 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -5,7 +5,6 @@
use actix_web::{web, HttpRequest, Responder};
use api_models::{enums, routing as routing_types, routing::RoutingRetrieveQuery};
-use common_enums::EntityType;
use router_env::{
tracing::{self, instrument},
Flow,
@@ -44,15 +43,13 @@ pub async fn routing_create_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -87,15 +84,13 @@ pub async fn routing_link_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -137,16 +132,14 @@ pub async fn routing_link_config(
&auth::ApiKeyAuth,
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -180,15 +173,13 @@ pub async fn routing_retrieve_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -222,15 +213,13 @@ pub async fn list_routing_configs(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -264,15 +253,13 @@ pub async fn list_routing_configs_for_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -308,16 +295,14 @@ pub async fn routing_unlink_config(
&auth::ApiKeyAuth,
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -352,15 +337,13 @@ pub async fn routing_unlink_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -397,15 +380,13 @@ pub async fn routing_update_default_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -437,15 +418,13 @@ pub async fn routing_update_default_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -478,16 +457,14 @@ pub async fn routing_retrieve_default_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -513,15 +490,13 @@ pub async fn routing_retrieve_default_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -553,15 +528,13 @@ pub async fn upsert_surcharge_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -590,15 +563,13 @@ pub async fn delete_surcharge_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -627,15 +598,13 @@ pub async fn retrieve_surcharge_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -667,15 +636,13 @@ pub async fn upsert_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -705,15 +672,13 @@ pub async fn delete_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -739,15 +704,13 @@ pub async fn retrieve_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -786,16 +749,14 @@ pub async fn routing_retrieve_linked_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -820,15 +781,13 @@ pub async fn routing_retrieve_linked_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -871,16 +830,14 @@ pub async fn routing_retrieve_linked_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -911,8 +868,7 @@ pub async fn routing_retrieve_default_config_for_profiles(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
@@ -920,8 +876,7 @@ pub async fn routing_retrieve_default_config_for_profiles(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
@@ -963,16 +918,14 @@ pub async fn routing_update_default_config_for_profile(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -1013,8 +966,7 @@ pub async fn toggle_success_based_routing(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index e07a2fa10ef..f52d0dca7a8 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -5,7 +5,7 @@ use api_models::{
errors::types::ApiErrorResponse,
user::{self as user_api},
};
-use common_enums::{EntityType, TokenPurpose};
+use common_enums::TokenPurpose;
use common_utils::errors::ReportSwitchExt;
use router_env::Flow;
@@ -176,8 +176,7 @@ pub async fn set_dashboard_metadata(
payload,
user_core::dashboard_metadata::set_metadata,
&auth::JWTAuth {
- permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -243,8 +242,7 @@ pub async fn user_merchant_account_create(
user_core::create_merchant_account(state, auth, json_payload)
},
&auth::JWTAuth {
- permission: Permission::MerchantAccountCreate,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::OrganizationAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -267,8 +265,7 @@ pub async fn generate_sample_data(
payload.into_inner(),
sample_data::generate_sample_data_for_user,
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -292,7 +289,6 @@ pub async fn delete_sample_data(
sample_data::delete_sample_data_for_user,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -312,8 +308,7 @@ pub async fn list_user_roles_details(
payload.into_inner(),
user_core::list_user_roles_details,
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -395,8 +390,7 @@ pub async fn invite_multiple_user(
user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone())
},
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -421,8 +415,7 @@ pub async fn resend_invite(
user_core::resend_invite(state, user, req_payload, auth_id.clone())
},
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -504,8 +497,7 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques
(),
|state, user, _req, _| user_core::verify_token(state, user),
&auth::JWTAuth {
- permission: Permission::ReconAdmin,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReconWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 777cbe1fd95..74847f06474 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,6 +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::{EntityType, TokenPurpose};
+use common_enums::TokenPurpose;
use router_env::Flow;
use super::AppState;
@@ -31,8 +31,7 @@ pub async fn get_authorization_info(
user_role_core::get_authorization_info_with_groups(state).await
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -69,8 +68,7 @@ pub async fn create_role(
json_payload.into_inner(),
role_core::create_role,
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -95,8 +93,7 @@ pub async fn get_role(
role_core::get_role_with_groups(state, user, payload).await
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -119,8 +116,7 @@ pub async fn update_role(
json_payload.into_inner(),
|state, user, req, _| role_core::update_role(state, user, req, &role_id),
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -141,8 +137,7 @@ pub async fn update_user_role(
payload,
user_role_core::update_user_role,
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -202,8 +197,7 @@ pub async fn delete_user_role(
payload.into_inner(),
user_role_core::delete_user_role,
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -225,8 +219,7 @@ pub async fn get_role_information(
user_role_core::get_authorization_info_with_group_tag().await
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -270,8 +263,7 @@ pub async fn list_roles_with_info(
role_core::list_roles_with_info(state, user_from_token, request)
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -299,8 +291,7 @@ pub async fn list_invitable_roles_at_entity_level(
)
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -328,8 +319,7 @@ pub async fn list_updatable_roles_at_entity_level(
)
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs
index 17c946c4810..56ad42947c2 100644
--- a/crates/router/src/routes/verification.rs
+++ b/crates/router/src/routes/verification.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, Responder};
use api_models::verifications;
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -34,8 +33,7 @@ pub async fn apple_pay_merchant_registration(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
@@ -70,7 +68,6 @@ pub async fn retrieve_apple_pay_verified_domains(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs
index 29f8c154bc0..b8e089f0660 100644
--- a/crates/router/src/routes/verify_connector.rs
+++ b/crates/router/src/routes/verify_connector.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::verify_connector::VerifyConnectorRequest;
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::AppState;
@@ -25,8 +24,7 @@ pub async fn payment_connector_verify(
verify_connector::verify_connector_credentials(state, req, auth.profile_id)
},
&auth::JWTAuth {
- permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs
index 8b94fb61f56..5039f72db31 100644
--- a/crates/router/src/routes/webhook_events.rs
+++ b/crates/router/src/routes/webhook_events.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, Responder};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use crate::{
@@ -44,8 +43,7 @@ pub async fn list_initial_webhook_delivery_attempts(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::WebhookEventRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
@@ -84,8 +82,7 @@ pub async fn list_webhook_delivery_attempts(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::WebhookEventRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
@@ -124,8 +121,7 @@ pub async fn retry_webhook_delivery_attempt(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::WebhookEventWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantWebhookEventWrite,
},
req.headers(),
),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index b64c5d14f32..e6da2b23301 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -10,7 +10,7 @@ use api_models::payment_methods::PaymentMethodIntentConfirm;
use api_models::payouts;
use api_models::{payment_methods::PaymentMethodListRequest, payments};
use async_trait::async_trait;
-use common_enums::{EntityType, TokenPurpose};
+use common_enums::TokenPurpose;
use common_utils::{date_time, id_type};
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
@@ -1232,7 +1232,6 @@ where
#[derive(Debug)]
pub(crate) struct JWTAuth {
pub permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1252,7 +1251,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
Ok((
(),
@@ -1282,7 +1280,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
Ok((
UserFromToken {
@@ -1318,7 +1315,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -1359,7 +1355,6 @@ where
pub struct JWTAuthOrganizationFromRoute {
pub organization_id: id_type::OrganizationId,
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1379,7 +1374,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
// Check if token has access to Organization that has been requested in the route
if payload.org_id != self.organization_id {
@@ -1398,12 +1392,10 @@ where
pub struct JWTAuthMerchantFromRoute {
pub merchant_id: id_type::MerchantId,
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
pub struct JWTAuthMerchantFromHeader {
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1423,7 +1415,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
@@ -1459,7 +1450,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
@@ -1526,7 +1516,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
// Check if token has access to MerchantId that has been requested through query param
if payload.merchant_id != self.merchant_id {
@@ -1563,7 +1552,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -1606,7 +1594,6 @@ pub struct JWTAuthMerchantAndProfileFromRoute {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1638,7 +1625,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -1682,7 +1668,6 @@ where
pub struct JWTAuthProfileFromRoute {
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1702,7 +1687,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -1798,7 +1782,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -1859,7 +1842,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -1923,7 +1905,6 @@ where
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
@@ -2349,7 +2330,6 @@ where
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
- authorization::check_entity(self.minimum_entity_level, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index 78af4c00884..fe6ffac6ffc 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -112,18 +112,6 @@ pub fn check_permission(
)
}
-pub fn check_entity(
- required_minimum_entity: common_enums::EntityType,
- role_info: &roles::RoleInfo,
-) -> RouterResult<()> {
- if required_minimum_entity > role_info.get_entity_type() {
- Err(ApiErrorResponse::AccessForbidden {
- resource: required_minimum_entity.to_string(),
- })?;
- }
- Ok(())
-}
-
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 031e0b56729..dba96dac188 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,5 +1,5 @@
-use api_models::user_role::{GroupInfo, ParentGroup};
-use common_enums::PermissionGroup;
+use api_models::user_role::GroupInfo;
+use common_enums::{ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
index aafc9cee943..3d1a0c8ea5b 100644
--- a/crates/router/src/services/authorization/permission_groups.rs
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -1,97 +1,122 @@
-use common_enums::PermissionGroup;
-
-use super::permissions::Permission;
-
-pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] {
- match permission_group {
- PermissionGroup::OperationsView => &OPERATIONS_VIEW,
- PermissionGroup::OperationsManage => &OPERATIONS_MANAGE,
- PermissionGroup::ConnectorsView => &CONNECTORS_VIEW,
- PermissionGroup::ConnectorsManage => &CONNECTORS_MANAGE,
- PermissionGroup::WorkflowsView => &WORKFLOWS_VIEW,
- PermissionGroup::WorkflowsManage => &WORKFLOWS_MANAGE,
- PermissionGroup::AnalyticsView => &ANALYTICS_VIEW,
- PermissionGroup::UsersView => &USERS_VIEW,
- PermissionGroup::UsersManage => &USERS_MANAGE,
- PermissionGroup::MerchantDetailsView => &MERCHANT_DETAILS_VIEW,
- PermissionGroup::MerchantDetailsManage => &MERCHANT_DETAILS_MANAGE,
- PermissionGroup::OrganizationManage => &ORGANIZATION_MANAGE,
- PermissionGroup::ReconOps => &RECON,
- }
+use common_enums::{ParentGroup, PermissionGroup, PermissionScope, Resource};
+
+pub trait PermissionGroupExt {
+ fn scope(&self) -> PermissionScope;
+ fn parent(&self) -> ParentGroup;
+ fn resources(&self) -> Vec<Resource>;
+ fn accessible_groups(&self) -> Vec<PermissionGroup>;
}
-pub static OPERATIONS_VIEW: [Permission; 8] = [
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::MandateRead,
- Permission::DisputeRead,
- Permission::CustomerRead,
- Permission::GenerateReport,
- Permission::PayoutRead,
- Permission::MerchantAccountRead,
-];
+impl PermissionGroupExt for PermissionGroup {
+ fn scope(&self) -> PermissionScope {
+ match self {
+ Self::OperationsView
+ | Self::ConnectorsView
+ | Self::WorkflowsView
+ | Self::AnalyticsView
+ | Self::UsersView
+ | Self::MerchantDetailsView => PermissionScope::Read,
-pub static OPERATIONS_MANAGE: [Permission; 7] = [
- Permission::PaymentWrite,
- Permission::RefundWrite,
- Permission::MandateWrite,
- Permission::DisputeWrite,
- Permission::CustomerWrite,
- Permission::PayoutWrite,
- Permission::MerchantAccountRead,
-];
+ Self::OperationsManage
+ | Self::ConnectorsManage
+ | Self::WorkflowsManage
+ | Self::UsersManage
+ | Self::MerchantDetailsManage
+ | Self::OrganizationManage
+ | Self::ReconOps => PermissionScope::Write,
+ }
+ }
-pub static CONNECTORS_VIEW: [Permission; 2] = [
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantAccountRead,
-];
+ fn parent(&self) -> ParentGroup {
+ match self {
+ Self::OperationsView | Self::OperationsManage => ParentGroup::Operations,
+ Self::ConnectorsView | Self::ConnectorsManage => ParentGroup::Connectors,
+ Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows,
+ Self::AnalyticsView => ParentGroup::Analytics,
+ Self::UsersView | Self::UsersManage => ParentGroup::Users,
+ Self::MerchantDetailsView | Self::MerchantDetailsManage => ParentGroup::Merchant,
+ Self::OrganizationManage => ParentGroup::Organization,
+ Self::ReconOps => ParentGroup::Recon,
+ }
+ }
-pub static CONNECTORS_MANAGE: [Permission; 2] = [
- Permission::MerchantConnectorAccountWrite,
- Permission::MerchantAccountRead,
-];
+ fn resources(&self) -> Vec<Resource> {
+ self.parent().resources()
+ }
-pub static WORKFLOWS_VIEW: [Permission; 5] = [
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantAccountRead,
-];
+ fn accessible_groups(&self) -> Vec<Self> {
+ match self {
+ Self::OperationsView => vec![Self::OperationsView],
+ Self::OperationsManage => vec![Self::OperationsView, Self::OperationsManage],
-pub static WORKFLOWS_MANAGE: [Permission; 5] = [
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::SurchargeDecisionManagerWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantAccountRead,
-];
+ Self::ConnectorsView => vec![Self::ConnectorsView],
+ Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage],
-pub static ANALYTICS_VIEW: [Permission; 3] = [
- Permission::Analytics,
- Permission::GenerateReport,
- Permission::MerchantAccountRead,
-];
+ Self::WorkflowsView => vec![Self::WorkflowsView],
+ Self::WorkflowsManage => vec![Self::WorkflowsView, Self::WorkflowsManage],
+
+ Self::AnalyticsView => vec![Self::AnalyticsView],
-pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead];
+ Self::UsersView => vec![Self::UsersView],
+ Self::UsersManage => {
+ vec![Self::UsersView, Self::UsersManage]
+ }
-pub static USERS_MANAGE: [Permission; 2] =
- [Permission::UsersWrite, Permission::MerchantAccountRead];
+ Self::ReconOps => vec![Self::ReconOps],
-pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead];
+ Self::MerchantDetailsView => vec![Self::MerchantDetailsView],
+ Self::MerchantDetailsManage => {
+ vec![Self::MerchantDetailsView, Self::MerchantDetailsManage]
+ }
-pub static MERCHANT_DETAILS_MANAGE: [Permission; 6] = [
- Permission::MerchantAccountWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::WebhookEventRead,
- Permission::WebhookEventWrite,
+ Self::OrganizationManage => vec![Self::OrganizationManage],
+ }
+ }
+}
+
+pub trait ParentGroupExt {
+ fn resources(&self) -> Vec<Resource>;
+}
+
+impl ParentGroupExt for ParentGroup {
+ fn resources(&self) -> Vec<Resource> {
+ match self {
+ Self::Operations => OPERATIONS.to_vec(),
+ Self::Connectors => CONNECTORS.to_vec(),
+ Self::Workflows => WORKFLOWS.to_vec(),
+ Self::Analytics => ANALYTICS.to_vec(),
+ Self::Users => USERS.to_vec(),
+ Self::Merchant | Self::Organization => ACCOUNT.to_vec(),
+ Self::Recon => RECON.to_vec(),
+ }
+ }
+}
+
+pub static OPERATIONS: [Resource; 8] = [
+ Resource::Payment,
+ Resource::Refund,
+ Resource::Mandate,
+ Resource::Dispute,
+ Resource::Customer,
+ Resource::Payout,
+ Resource::Report,
+ Resource::Account,
];
-pub static ORGANIZATION_MANAGE: [Permission; 2] = [
- Permission::MerchantAccountCreate,
- Permission::MerchantAccountRead,
+pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account];
+
+pub static WORKFLOWS: [Resource; 5] = [
+ Resource::Routing,
+ Resource::ThreeDsDecisionManager,
+ Resource::SurchargeDecisionManager,
+ Resource::Connector,
+ Resource::Account,
];
-pub static RECON: [Permission; 1] = [Permission::ReconAdmin];
+pub static ANALYTICS: [Resource; 3] = [Resource::Analytics, Resource::Report, Resource::Account];
+
+pub static USERS: [Resource; 2] = [Resource::User, Resource::Account];
+
+pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent];
+
+pub static RECON: [Resource; 1] = [Resource::Recon];
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 2121ba0f944..0521db7acc1 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -1,39 +1,75 @@
-use strum::Display;
+use common_enums::{EntityType, PermissionScope, Resource};
+use router_derive::generate_permissions;
-#[derive(
- PartialEq, Display, Clone, Debug, Copy, Eq, Hash, serde::Deserialize, serde::Serialize,
-)]
-pub enum Permission {
- PaymentRead,
- PaymentWrite,
- RefundRead,
- RefundWrite,
- ApiKeyRead,
- ApiKeyWrite,
- MerchantAccountRead,
- MerchantAccountWrite,
- MerchantConnectorAccountRead,
- MerchantConnectorAccountWrite,
- RoutingRead,
- RoutingWrite,
- DisputeRead,
- DisputeWrite,
- MandateRead,
- MandateWrite,
- CustomerRead,
- CustomerWrite,
- Analytics,
- ThreeDsDecisionManagerWrite,
- ThreeDsDecisionManagerRead,
- SurchargeDecisionManagerWrite,
- SurchargeDecisionManagerRead,
- UsersRead,
- UsersWrite,
- MerchantAccountCreate,
- WebhookEventRead,
- WebhookEventWrite,
- PayoutRead,
- PayoutWrite,
- GenerateReport,
- ReconAdmin,
+generate_permissions! {
+ permissions: [
+ Payment: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Refund: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Dispute: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Mandate: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Customer: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Payout: {
+ scopes: [Read],
+ entities: [Profile, Merchant]
+ },
+ ApiKey: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Account: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant, Organization]
+ },
+ Connector: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Routing: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ ThreeDsDecisionManager: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ SurchargeDecisionManager: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Analytics: {
+ scopes: [Read],
+ entities: [Profile, Merchant, Organization]
+ },
+ Report: {
+ scopes: [Read],
+ entities: [Profile, Merchant, Organization]
+ },
+ User: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ WebhookEvent: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Recon: {
+ scopes: [Write],
+ entities: [Merchant]
+ },
+ ]
}
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index 19383f010f2..63d547bfa67 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -1,9 +1,9 @@
use std::collections::HashSet;
-use common_enums::{EntityType, PermissionGroup, RoleScope};
+use common_enums::{EntityType, PermissionGroup, Resource, RoleScope};
use common_utils::{errors::CustomResult, id_type};
-use super::{permission_groups::get_permissions_vec, permissions::Permission};
+use super::{permission_groups::PermissionGroupExt, permissions::Permission};
use crate::{core::errors, routes::SessionState};
pub mod predefined_roles;
@@ -30,8 +30,13 @@ impl RoleInfo {
&self.role_name
}
- pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> {
- &self.groups
+ pub fn get_permission_groups(&self) -> Vec<PermissionGroup> {
+ self.groups
+ .iter()
+ .flat_map(|group| group.accessible_groups())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect()
}
pub fn get_scope(&self) -> RoleScope {
@@ -58,17 +63,19 @@ impl RoleInfo {
self.is_updatable
}
- pub fn get_permissions_set(&self) -> HashSet<Permission> {
- self.groups
+ pub fn get_resources_set(&self) -> HashSet<Resource> {
+ self.get_permission_groups()
.iter()
- .flat_map(|group| get_permissions_vec(group).iter().copied())
+ .flat_map(|group| group.resources())
.collect()
}
pub fn check_permission_exists(&self, required_permission: &Permission) -> bool {
- self.groups
- .iter()
- .any(|group| get_permissions_vec(group).contains(required_permission))
+ required_permission.entity_type() <= self.entity_type
+ && self.get_permission_groups().iter().any(|group| {
+ required_permission.scope() <= group.scope()
+ && group.resources().contains(&required_permission.resource())
+ })
}
pub async fn from_role_id_in_merchant_scope(
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs
index 02179934e38..69865512a37 100644
--- a/crates/router_derive/src/lib.rs
+++ b/crates/router_derive/src/lib.rs
@@ -694,3 +694,58 @@ pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenSt
proc_macro::TokenStream::from(expanded)
}
+
+/// Generates the permissions enum and implematations for the permissions
+///
+/// **NOTE:** You have to make sure that all the identifiers used
+/// in the macro input are present in the respective enums as well.
+///
+/// ## Usage
+/// ```
+/// use router_derive::generate_permissions;
+///
+/// enum Scope {
+/// Read,
+/// Write,
+/// }
+///
+/// enum EntityType {
+/// Profile,
+/// Merchant,
+/// Org,
+/// }
+///
+/// enum Resource {
+/// Payments,
+/// Refunds,
+/// }
+///
+/// generate_permissions! {
+/// permissions: [
+/// Payments: {
+/// scopes: [Read, Write],
+/// entities: [Profile, Merchant, Org]
+/// },
+/// Refunds: {
+/// scopes: [Read],
+/// entities: [Profile, Org]
+/// }
+/// ]
+/// }
+/// ```
+/// This will generate the following enum.
+/// ```
+/// enum Permission {
+/// ProfilePaymentsRead,
+/// ProfilePaymentsWrite,
+/// MerchantPaymentsRead,
+/// MerchantPaymentsWrite,
+/// OrgPaymentsRead,
+/// OrgPaymentsWrite,
+/// ProfileRefundsRead,
+/// OrgRefundsRead,
+/// ```
+#[proc_macro]
+pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ macros::generate_permissions_inner(input)
+}
diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs
index 9a8e514c5c1..32e6c213ca6 100644
--- a/crates/router_derive/src/macros.rs
+++ b/crates/router_derive/src/macros.rs
@@ -1,5 +1,6 @@
pub(crate) mod api_error;
pub(crate) mod diesel;
+pub(crate) mod generate_permissions;
pub(crate) mod generate_schema;
pub(crate) mod misc;
pub(crate) mod operation;
@@ -14,6 +15,7 @@ use syn::DeriveInput;
pub(crate) use self::{
api_error::api_error_derive_inner,
diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner},
+ generate_permissions::generate_permissions_inner,
generate_schema::polymorphic_macro_derive_inner,
};
diff --git a/crates/router_derive/src/macros/generate_permissions.rs b/crates/router_derive/src/macros/generate_permissions.rs
new file mode 100644
index 00000000000..9b388f102cb
--- /dev/null
+++ b/crates/router_derive/src/macros/generate_permissions.rs
@@ -0,0 +1,135 @@
+use proc_macro::TokenStream;
+use quote::{format_ident, quote};
+use syn::{
+ braced, bracketed,
+ parse::{Parse, ParseBuffer, ParseStream},
+ parse_macro_input,
+ punctuated::Punctuated,
+ token::Comma,
+ Ident, Token,
+};
+
+struct ResourceInput {
+ resource_name: Ident,
+ scopes: Punctuated<Ident, Token![,]>,
+ entities: Punctuated<Ident, Token![,]>,
+}
+
+struct Input {
+ permissions: Punctuated<ResourceInput, Token![,]>,
+}
+
+impl Parse for Input {
+ fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
+ let (_permission_label, permissions) = parse_label_with_punctuated_data(input)?;
+
+ Ok(Self { permissions })
+ }
+}
+
+impl Parse for ResourceInput {
+ fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
+ let resource_name: Ident = input.parse()?;
+ input.parse::<Token![:]>()?; // Expect ':'
+
+ let content;
+ braced!(content in input);
+
+ let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?;
+ content.parse::<Comma>()?;
+
+ let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?;
+
+ Ok(Self {
+ resource_name,
+ scopes,
+ entities,
+ })
+ }
+}
+
+fn parse_label_with_punctuated_data<T: Parse>(
+ input: &ParseBuffer<'_>,
+) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> {
+ let label: Ident = input.parse()?;
+ input.parse::<Token![:]>()?; // Expect ':'
+
+ let content;
+ bracketed!(content in input); // Parse the list inside []
+ let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?;
+
+ Ok((label, data))
+}
+
+pub fn generate_permissions_inner(input: TokenStream) -> TokenStream {
+ let input = parse_macro_input!(input as Input);
+
+ let res = input.permissions.iter();
+
+ let mut enum_keys = Vec::new();
+ let mut scope_impl_per = Vec::new();
+ let mut entity_impl_per = Vec::new();
+ let mut resource_impl_per = Vec::new();
+
+ let mut entity_impl_res = Vec::new();
+
+ for per in res {
+ let resource_name = &per.resource_name;
+ let mut permissions = Vec::new();
+
+ for scope in per.scopes.iter() {
+ for entity in per.entities.iter() {
+ let key = format_ident!("{}{}{}", entity, per.resource_name, scope);
+
+ enum_keys.push(quote! { #key });
+ scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope });
+ entity_impl_per.push(quote! { Permission::#key => EntityType::#entity });
+ resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name });
+ permissions.push(quote! { Permission::#key });
+ }
+ let entities_iter = per.entities.iter();
+ entity_impl_res
+ .push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] });
+ }
+ }
+
+ let expanded = quote! {
+ #[derive(
+ Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display
+ )]
+ pub enum Permission {
+ #(#enum_keys),*
+ }
+
+ impl Permission {
+ pub fn scope(&self) -> PermissionScope {
+ match self {
+ #(#scope_impl_per),*
+ }
+ }
+ pub fn entity_type(&self) -> EntityType {
+ match self {
+ #(#entity_impl_per),*
+ }
+ }
+ pub fn resource(&self) -> Resource {
+ match self {
+ #(#resource_impl_per),*
+ }
+ }
+ }
+
+ pub trait ResourceExt {
+ fn entities(&self) -> Vec<EntityType>;
+ }
+
+ impl ResourceExt for Resource {
+ fn entities(&self) -> Vec<EntityType> {
+ match self {
+ #(#entity_impl_res),*
+ }
+ }
+ }
+ };
+ expanded.into()
+}
|
feat
|
Create a permission generator (#6394)
|
10944937a02502e0727f16368d8d055e575dd518
|
2023-11-02 17:53:35
|
Sampras Lopes
|
feat(events): add api auth type details to events (#2760)
| false
|
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index 8a1bf3f6aed..75cb07de02b 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -28,7 +28,6 @@ where
Q: Serialize + std::fmt::Debug + 'a,
S: TryFrom<Q> + Serialize,
E: Serialize + error_stack::Context + actix_web::ResponseError + Clone,
- U: auth::AuthInfo,
error_stack::Report<E>: services::EmbedError,
errors::ApiErrorResponse: ErrorSwitch<E>,
T: std::fmt::Debug + Serialize,
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs
index 5e031fd945f..35eaf1edae7 100644
--- a/crates/router/src/events/api_logs.rs
+++ b/crates/router/src/events/api_logs.rs
@@ -1,16 +1,19 @@
use router_env::{tracing_actix_web::RequestId, types::FlowMetric};
-use serde::{Deserialize, Serialize};
+use serde::Serialize;
use time::OffsetDateTime;
use super::{EventType, RawEvent};
+use crate::services::authentication::AuthenticationType;
-#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ApiEvent {
api_flow: String,
created_at_timestamp: i128,
request_id: String,
latency: u128,
status_code: i64,
+ #[serde(flatten)]
+ auth_type: AuthenticationType,
request: serde_json::Value,
response: Option<serde_json::Value>,
}
@@ -23,6 +26,7 @@ impl ApiEvent {
status_code: i64,
request: serde_json::Value,
response: Option<serde_json::Value>,
+ auth_type: AuthenticationType,
) -> Self {
Self {
api_flow: api_flow.to_string(),
@@ -32,6 +36,7 @@ impl ApiEvent {
status_code,
request,
response,
+ auth_type,
}
}
}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index cb94312b0e2..a1e657c7d92 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -25,7 +25,7 @@ use serde_json::json;
use tera::{Context, Tera};
use self::request::{HeaderExt, RequestBuilderExt};
-use super::authentication::{AuthInfo, AuthenticateAndFetch};
+use super::authentication::AuthenticateAndFetch;
use crate::{
configs::settings::{Connectors, Settings},
consts,
@@ -761,7 +761,6 @@ where
Q: Serialize + Debug + 'a,
T: Debug + Serialize,
A: AppStateInfo + Clone,
- U: AuthInfo,
E: ErrorSwitch<OErr> + error_stack::Context,
OErr: ResponseError + error_stack::Context,
errors::ApiErrorResponse: ErrorSwitch<OErr>,
@@ -782,12 +781,12 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
// Currently auth failures are not recorded as API events
- let auth_out = api_auth
+ let (auth_out, auth_type) = api_auth
.authenticate_and_fetch(request.headers(), &request_state)
.await
.switch()?;
- let merchant_id = auth_out
+ let merchant_id = auth_type
.get_merchant_id()
.unwrap_or("MERCHANT_ID_NOT_FOUND")
.to_string();
@@ -841,6 +840,7 @@ where
status_code,
serialized_request,
serialized_response,
+ auth_type,
);
match api_event.clone().try_into() {
Ok(event) => {
@@ -874,7 +874,6 @@ where
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a,
T: Debug + Serialize,
- U: AuthInfo,
A: AppStateInfo + Clone,
ApplicationResponse<Q>: Debug,
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index eec872a9f34..faa7864aff5 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -7,6 +7,7 @@ use error_stack::{report, IntoReport, ResultExt};
use external_services::kms::{self, decrypt::KmsDecrypt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use masking::{PeekInterface, StrongSecret};
+use serde::Serialize;
use crate::{
configs::settings,
@@ -21,11 +22,51 @@ use crate::{
utils::OptionExt,
};
+#[derive(Clone, Debug)]
pub struct AuthenticationData {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
}
+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
+#[serde(tag = "api_auth_type")]
+pub enum AuthenticationType {
+ ApiKey {
+ merchant_id: String,
+ key_id: String,
+ },
+ AdminApiKey,
+ MerchantJWT {
+ merchant_id: String,
+ user_id: Option<String>,
+ },
+ MerchantID {
+ merchant_id: String,
+ },
+ PublishableKey {
+ merchant_id: String,
+ },
+ NoAuth,
+}
+
+impl AuthenticationType {
+ pub fn get_merchant_id(&self) -> Option<&str> {
+ match self {
+ Self::ApiKey {
+ merchant_id,
+ key_id: _,
+ }
+ | Self::MerchantID { merchant_id }
+ | Self::PublishableKey { merchant_id }
+ | Self::MerchantJWT {
+ merchant_id,
+ user_id: _,
+ } => Some(merchant_id.as_ref()),
+ Self::AdminApiKey | Self::NoAuth => None,
+ }
+ }
+}
+
pub trait AuthInfo {
fn get_merchant_id(&self) -> Option<&str>;
}
@@ -46,13 +87,12 @@ impl AuthInfo for AuthenticationData {
pub trait AuthenticateAndFetch<T, A>
where
A: AppStateInfo,
- T: AuthInfo,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<T>;
+ ) -> RouterResult<(T, AuthenticationType)>;
}
#[derive(Debug)]
@@ -69,8 +109,8 @@ where
&self,
_request_headers: &HeaderMap,
_state: &A,
- ) -> RouterResult<()> {
- Ok(())
+ ) -> RouterResult<((), AuthenticationType)> {
+ Ok(((), AuthenticationType::NoAuth))
}
}
@@ -83,7 +123,7 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<AuthenticationData> {
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
@@ -139,10 +179,17 @@ where
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
- Ok(AuthenticationData {
+ let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- })
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::ApiKey {
+ merchant_id: auth.merchant_account.merchant_id.clone(),
+ key_id: stored_api_key.key_id,
+ },
+ ))
}
}
@@ -183,7 +230,7 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<()> {
+ ) -> RouterResult<((), AuthenticationType)> {
let request_admin_api_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let conf = state.conf();
@@ -200,7 +247,7 @@ where
.attach_printable("Admin Authentication Failure"))?;
}
- Ok(())
+ Ok(((), AuthenticationType::AdminApiKey))
}
}
@@ -216,7 +263,7 @@ where
&self,
_request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<AuthenticationData> {
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
@@ -245,10 +292,16 @@ where
}
})?;
- Ok(AuthenticationData {
+ let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- })
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::MerchantID {
+ merchant_id: auth.merchant_account.merchant_id.clone(),
+ },
+ ))
}
}
@@ -264,7 +317,7 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<AuthenticationData> {
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let publishable_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
@@ -279,6 +332,14 @@ where
e.change_context(errors::ApiErrorResponse::InternalServerError)
}
})
+ .map(|auth| {
+ (
+ auth.clone(),
+ AuthenticationType::PublishableKey {
+ merchant_id: auth.merchant_account.merchant_id.clone(),
+ },
+ )
+ })
}
}
@@ -300,12 +361,12 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<()> {
+ ) -> RouterResult<((), AuthenticationType)> {
let mut token = get_jwt(request_headers)?;
token = strip_jwt_token(token)?;
decode_jwt::<JwtAuthPayloadFetchUnit>(token, state)
.await
- .map(|_| ())
+ .map(|_| ((), AuthenticationType::NoAuth))
}
}
@@ -323,7 +384,7 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<AuthenticationData> {
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let mut token = get_jwt(request_headers)?;
token = strip_jwt_token(token)?;
let payload = decode_jwt::<JwtAuthPayloadFetchMerchantAccount>(token, state).await?;
@@ -343,10 +404,17 @@ where
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
- Ok(AuthenticationData {
+ let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- })
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::MerchantJWT {
+ merchant_id: auth.merchant_account.merchant_id.clone(),
+ user_id: None,
+ },
+ ))
}
}
|
feat
|
add api auth type details to events (#2760)
|
b090e421e4880d156fa17048bf63c8f4d4b40395
|
2023-01-11 16:13:36
|
Nishant Joshi
|
fix: fix refund amount in `RefundNew` (#349)
| false
|
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 102a82ab6b4..78f9cac31bd 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -46,8 +46,7 @@ pub async fn refund_create_core(
// Amount is not passed in request refer from payment attempt.
amount = req.amount.unwrap_or(payment_attempt.amount); // [#298]: Need to that capture amount
-
- //[#299]: Can we change the flow based on some workflow idea
+ //[#299]: Can we change the flow based on some workflow idea
utils::when(amount <= 0, || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount".to_string(),
@@ -438,7 +437,8 @@ pub async fn validate_and_create_refund(
.set_connector_transaction_id(connecter_transaction_id.to_string())
.set_connector(connector)
.set_refund_type(enums::RefundType::RegularRefund)
- .set_total_amount(refund_amount)
+ .set_total_amount(payment_attempt.amount)
+ .set_refund_amount(refund_amount)
.set_currency(currency)
.set_created_at(Some(common_utils::date_time::now()))
.set_modified_at(Some(common_utils::date_time::now()))
|
fix
|
fix refund amount in `RefundNew` (#349)
|
e5ea411fb05a1bc7e59a58753b645015e7a4c7f4
|
2022-12-15 19:43:44
|
Nishant Joshi
|
feat(admin): add `payment_connector_list` API (#160)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index bb6e24c2b93..b58e0763563 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1825,6 +1825,16 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "libmimalloc-sys"
+version = "0.1.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04d1c67deb83e6b75fa4fe3309e09cfeade12e7721d95322af500d3814ea60c9"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "libz-sys"
version = "1.1.8"
@@ -1943,6 +1953,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
+[[package]]
+name = "mimalloc"
+version = "0.1.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b2374e2999959a7b583e1811a1ddbf1d3a4b9496eceb9746f1192a59d871eca"
+dependencies = [
+ "libmimalloc-sys",
+]
+
[[package]]
name = "mime"
version = "0.3.16"
@@ -2712,6 +2731,7 @@ dependencies = [
"literally",
"masking",
"maud",
+ "mimalloc",
"mime",
"nanoid",
"once_cell",
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 51a245e9fe2..21968854a9c 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -10,7 +10,7 @@ use crate::{
types::{
self, api,
storage::{self, MerchantAccount},
- transformers::ForeignInto,
+ transformers::{ForeignInto, ForeignTryInto},
},
utils::{self, OptionExt, ValueExt},
};
@@ -356,22 +356,35 @@ pub async fn retrieve_payment_connector(
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)
})?;
- let payment_methods_enabled = match mca.payment_methods_enabled {
- Some(val) => serde_json::Value::Array(val)
- .parse_value("PaymentMethods")
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- None => None,
- };
- let response = api::PaymentConnectorCreate {
- connector_type: mca.connector_type.foreign_into(),
- connector_name: mca.connector_name,
- merchant_connector_id: Some(mca.merchant_connector_id),
- connector_account_details: Some(Secret::new(mca.connector_account_details)),
- test_mode: mca.test_mode,
- disabled: mca.disabled,
- payment_methods_enabled,
- metadata: None,
- };
+
+ Ok(service_api::BachResponse::Json(mca.foreign_try_into()?))
+}
+
+pub async fn list_payment_connectors(
+ store: &dyn StorageInterface,
+ merchant_id: String,
+) -> RouterResponse<Vec<api::PaymentConnectorCreate>> {
+ // Validate merchant account
+ store
+ .find_merchant_account_by_merchant_id(&merchant_id)
+ .await
+ .map_err(|err| {
+ err.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
+ })?;
+
+ let merchant_connector_accounts = store
+ .find_merchant_connector_account_by_merchant_id_list(&merchant_id)
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound)
+ })?;
+ let mut response = vec![];
+
+ // The can be eliminated once [#79711](https://github.com/rust-lang/rust/issues/79711) is stabilized
+ for mca in merchant_connector_accounts.into_iter() {
+ response.push(mca.foreign_try_into()?);
+ }
+
Ok(service_api::BachResponse::Json(response))
}
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index fe62d7d7249..6351cd8803a 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -130,6 +130,24 @@ pub async fn payment_connector_retrieve(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PaymentConnectorsList))]
+
+pub async fn payment_connector_list(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let merchant_id = path.into_inner();
+ api::server_wrap(
+ &state,
+ &req,
+ merchant_id,
+ |state, _, merchant_id| list_payment_connectors(&*state.store, merchant_id),
+ api::MerchantAuthentication::AdminApiKey,
+ )
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentConnectorsUpdate))]
// #[post("/{merchant_id}/connectors/{merchant_connector_id}")]
pub async fn payment_connector_update(
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 44c3775a582..456c0c3a414 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -177,7 +177,8 @@ impl MerchantConnectorAccount {
.app_data(web::Data::new(config))
.service(
web::resource("/{merchant_id}/connectors")
- .route(web::post().to(payment_connector_create)),
+ .route(web::post().to(payment_connector_create))
+ .route(web::get().to(payment_connector_list)),
)
.service(
web::resource("/{merchant_id}/payment_methods")
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 06a44549ef1..398f3c678c1 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1,6 +1,8 @@
use std::convert::TryInto;
use api_models::enums as api_enums;
+use common_utils::ext_traits::ValueExt;
+use error_stack::ResultExt;
use storage_models::enums as storage_enums;
use crate::{
@@ -321,3 +323,33 @@ impl<'a> From<F<&'a storage::Address>> for F<api_types::Address> {
.into()
}
}
+
+impl TryFrom<F<storage::MerchantConnectorAccount>>
+ for F<api_models::admin::PaymentConnectorCreate>
+{
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+ fn try_from(item: F<storage::MerchantConnectorAccount>) -> Result<Self, Self::Error> {
+ let merchant_ca = item.0;
+
+ let payment_methods_enabled = match merchant_ca.payment_methods_enabled {
+ Some(val) => serde_json::Value::Array(val)
+ .parse_value("PaymentMethods")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ None => None,
+ };
+
+ Ok(api_models::admin::PaymentConnectorCreate {
+ connector_type: merchant_ca.connector_type.foreign_into(),
+ connector_name: merchant_ca.connector_name,
+ merchant_connector_id: Some(merchant_ca.merchant_connector_id),
+ connector_account_details: Some(masking::Secret::new(
+ merchant_ca.connector_account_details,
+ )),
+ test_mode: merchant_ca.test_mode,
+ disabled: merchant_ca.disabled,
+ metadata: None,
+ payment_methods_enabled,
+ }
+ .into())
+ }
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 93fc4ae4cee..c317f8a116e 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -70,6 +70,8 @@ pub enum Flow {
PaymentConnectorsUpdate,
/// Payment connectors delete flow.
PaymentConnectorsDelete,
+ /// Payment connectors list flow.
+ PaymentConnectorsList,
/// Customers create flow.
CustomersCreate,
/// Customers retrieve flow.
|
feat
|
add `payment_connector_list` API (#160)
|
6823418e2a6416fe964eaf756b6418738a5e74e0
|
2024-11-08 15:02:27
|
Rutam Prita Mishra
|
feat(payments): Add audit events for PaymentApprove update (#6432)
| false
|
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index fe5e7a7e72f..2bc18122b22 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -12,6 +12,7 @@ use crate::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentData},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -213,7 +214,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -257,6 +258,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ req_state
+ .event_context
+ .event(AuditEvent::new(AuditEventType::PaymentApprove))
+ .with(payment_data.to_event())
+ .emit();
Ok((Box::new(self), payment_data))
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 54c1934e36f..9fbd754b43c 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -27,6 +27,7 @@ pub enum AuditEventType {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
+ PaymentApprove,
PaymentCreate,
}
@@ -66,6 +67,7 @@ impl Event for AuditEvent {
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
+ AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
};
format!(
|
feat
|
Add audit events for PaymentApprove update (#6432)
|
a7c66ddea206ea1d22be6ddb1a503badf76fe2cf
|
2023-07-17 23:27:01
|
Panagiotis Ganelis
|
refactor(router): remove `WebhookApiErrorSwitch ` and implement error mapping using `ErrorSwitch` (#1660)
| false
|
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index d79e120c5c0..2ab8aff3a0a 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -1,5 +1,6 @@
pub mod api_error_response;
pub mod error_handlers;
+pub mod transformers;
pub mod utils;
use std::fmt::Display;
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index 6b0142f4bc0..7cdf2ab6c03 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -1,6 +1,5 @@
#![allow(dead_code, unused_variables)]
-use api_models::errors::types::Extra;
use http::StatusCode;
#[derive(Clone, Debug, serde::Serialize)]
@@ -261,244 +260,3 @@ impl actix_web::ResponseError for ApiErrorResponse {
}
impl crate::services::EmbedError for error_stack::Report<ApiErrorResponse> {}
-
-impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>
- for ApiErrorResponse
-{
- fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
- use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
-
- let error_message = self.error_message();
- let error_codes = self.error_code();
- let error_type = self.error_type();
-
- match self {
- Self::NotImplemented { message } => {
- AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
- }
- Self::Unauthorized => AER::Unauthorized(ApiError::new(
- "IR",
- 1,
- "API key not provided or invalid API key used", None
- )),
- Self::InvalidRequestUrl => {
- AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
- }
- Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
- "IR",
- 3,
- "The HTTP method is not applicable for this API", None
- )),
- Self::MissingRequiredField { field_name } => AER::BadRequest(
- ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
- ),
- Self::InvalidDataFormat {
- field_name,
- expected_format,
- } => AER::Unprocessable(ApiError::new(
- "IR",
- 5,
- format!(
- "{field_name} contains invalid data. Expected format is {expected_format}"
- ), None
- )),
- Self::InvalidRequestData { message } => {
- AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
- }
- Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
- "IR",
- 7,
- format!("Invalid value provided: {field_name}"), None
- )),
- Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
- "IR",
- 8,
- "client_secret was not provided", None
- )),
- Self::ClientSecretInvalid => {
- AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
- }
- Self::MandateActive => {
- AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
- }
- Self::CustomerRedacted => {
- AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
- }
- Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
- Self::RefundAmountExceedsPaymentAmount => {
- AER::BadRequest(ApiError::new("IR", 13, "Refund amount exceeds the payment amount", None))
- }
- Self::PaymentUnexpectedState {
- current_flow,
- field_name,
- current_value,
- states,
- } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
- Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
- Self::PreconditionFailed { message } => {
- AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
- }
- Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
- Self::GenericUnauthorized { message } => {
- AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
- },
- Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
- "IR",
- 19,
- "The provided client_secret has expired", None
- )),
- Self::MissingRequiredFields { field_names } => AER::BadRequest(
- ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
- ),
- Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)),
- Self::FileProviderNotSupported { message } => {
- AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
- },
- Self::UnprocessableEntity {entity} => AER::Unprocessable(ApiError::new("IR", 23, format!("{entity} expired or invalid"), None)),
- Self::ExternalConnectorError {
- code,
- message,
- connector,
- reason,
- status_code,
- } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.clone(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
- Self::PaymentAuthorizationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::PaymentAuthenticationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::PaymentCaptureFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::DisputeFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::VerificationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
- },
- Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {
- AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
- }
- Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
- Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
- Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
- Self::DuplicateMerchantConnectorAccount { connector_label } => {
- AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified connector_label '{connector_label}' already exists in our records"), None))
- }
- Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
- Self::DuplicatePayment { payment_id } => {
- AER::BadRequest(ApiError::new("HE", 1, format!("The payment with the specified payment_id '{payment_id}' already exists in our records"), None))
- }
- Self::RefundNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
- }
- Self::CustomerNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
- }
- Self::ConfigNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
- }
- Self::PaymentNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
- }
- Self::PaymentMethodNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
- }
- Self::MerchantAccountNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
- }
- Self::MerchantConnectorAccountNotFound { id } => {
- AER::NotFound(ApiError::new("HE", 2, format!("Merchant connector account with id '{id}' does not exist in our records"), None))
- }
- Self::MerchantConnectorAccountDisabled => {
- AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
- }
- Self::ResourceIdNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
- }
- Self::MandateNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
- }
- Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
- Self::RefundNotPossible { connector } => {
- AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
- }
- Self::MandateValidationFailed { reason } => {
- AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.clone()), ..Default::default() })))
- }
- Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
- Self::SuccessfulPaymentNotFound => {
- AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
- }
- Self::IncorrectConnectorNameGiven => {
- AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
- }
- Self::AddressNotFound => {
- AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
- },
- Self::GenericNotFoundError { message } => {
- AER::NotFound(ApiError::new("HE", 5, message, None))
- },
- Self::ApiKeyNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
- }
- Self::NotSupported { message } => {
- AER::BadRequest(ApiError::new("HE", 3, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
- },
- Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)),
- Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
- Self::FlowNotSupported { flow, connector } => {
- AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
- }
- Self::DisputeNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None))
- }
- Self::FileNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None))
- }
- Self::FileNotAvailable => {
- AER::NotFound(ApiError::new("HE", 2, "File not available", None))
- }
- Self::DisputeStatusValidationFailed { .. } => {
- AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None))
- }
- Self::FileValidationFailed { reason } => {
- AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None))
- }
- Self::MissingFile => {
- AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None))
- }
- Self::MissingFilePurpose => {
- AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None))
- }
- Self::MissingFileContentType => {
- AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None))
- }
- Self::MissingDisputeId => {
- AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None))
- }
- Self::WebhookAuthenticationFailed => {
- AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
- }
- Self::WebhookResourceNotFound => {
- AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
- }
- Self::WebhookBadRequest => {
- AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
- }
- Self::WebhookProcessingFailure => {
- AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
- },
- Self::IncorrectPaymentMethodConfiguration => {
- AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None))
- }
- Self::WebhookUnprocessableEntity => {
- AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
- }
- }
- }
-}
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
new file mode 100644
index 00000000000..facc453c587
--- /dev/null
+++ b/crates/router/src/core/errors/transformers.rs
@@ -0,0 +1,255 @@
+use api_models::errors::types::Extra;
+use common_utils::errors::ErrorSwitch;
+use http::StatusCode;
+
+use super::{ApiErrorResponse, ConnectorError};
+
+impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
+ fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
+ use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
+
+ match self {
+ Self::NotImplemented { message } => {
+ AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
+ }
+ Self::Unauthorized => AER::Unauthorized(ApiError::new(
+ "IR",
+ 1,
+ "API key not provided or invalid API key used", None
+ )),
+ Self::InvalidRequestUrl => {
+ AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
+ }
+ Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
+ "IR",
+ 3,
+ "The HTTP method is not applicable for this API", None
+ )),
+ Self::MissingRequiredField { field_name } => AER::BadRequest(
+ ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
+ ),
+ Self::InvalidDataFormat {
+ field_name,
+ expected_format,
+ } => AER::Unprocessable(ApiError::new(
+ "IR",
+ 5,
+ format!(
+ "{field_name} contains invalid data. Expected format is {expected_format}"
+ ), None
+ )),
+ Self::InvalidRequestData { message } => {
+ AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
+ }
+ Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
+ "IR",
+ 7,
+ format!("Invalid value provided: {field_name}"), None
+ )),
+ Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
+ "IR",
+ 8,
+ "client_secret was not provided", None
+ )),
+ Self::ClientSecretInvalid => {
+ AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
+ }
+ Self::MandateActive => {
+ AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
+ }
+ Self::CustomerRedacted => {
+ AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
+ }
+ Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
+ Self::RefundAmountExceedsPaymentAmount => {
+ AER::BadRequest(ApiError::new("IR", 13, "Refund amount exceeds the payment amount", None))
+ }
+ Self::PaymentUnexpectedState {
+ current_flow,
+ field_name,
+ current_value,
+ states,
+ } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
+ Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
+ Self::PreconditionFailed { message } => {
+ AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
+ }
+ Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
+ Self::GenericUnauthorized { message } => {
+ AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
+ },
+ Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
+ "IR",
+ 19,
+ "The provided client_secret has expired", None
+ )),
+ Self::MissingRequiredFields { field_names } => AER::BadRequest(
+ ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
+ ),
+ Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)),
+ Self::FileProviderNotSupported { message } => {
+ AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
+ },
+ Self::UnprocessableEntity {entity} => AER::Unprocessable(ApiError::new("IR", 23, format!("{entity} expired or invalid"), None)),
+ Self::ExternalConnectorError {
+ code,
+ message,
+ connector,
+ reason,
+ status_code,
+ } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.clone(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
+ Self::PaymentAuthorizationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::PaymentAuthenticationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::PaymentCaptureFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::DisputeFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::VerificationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
+ },
+ Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {
+ AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
+ }
+ Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
+ Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
+ Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
+ Self::DuplicateMerchantConnectorAccount { connector_label } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified connector_label '{connector_label}' already exists in our records"), None))
+ }
+ Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
+ Self::DuplicatePayment { payment_id } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The payment with the specified payment_id '{payment_id}' already exists in our records"), None))
+ }
+ Self::RefundNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
+ }
+ Self::CustomerNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
+ }
+ Self::ConfigNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
+ }
+ Self::PaymentNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
+ }
+ Self::PaymentMethodNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
+ }
+ Self::MerchantAccountNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
+ }
+ Self::MerchantConnectorAccountNotFound { id } => {
+ AER::NotFound(ApiError::new("HE", 2, format!("Merchant connector account with id '{id}' does not exist in our records"), None))
+ }
+ Self::MerchantConnectorAccountDisabled => {
+ AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
+ }
+ Self::ResourceIdNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
+ }
+ Self::MandateNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
+ }
+ Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
+ Self::RefundNotPossible { connector } => {
+ AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
+ }
+ Self::MandateValidationFailed { reason } => {
+ AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.clone()), ..Default::default() })))
+ }
+ Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
+ Self::SuccessfulPaymentNotFound => {
+ AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
+ }
+ Self::IncorrectConnectorNameGiven => {
+ AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
+ }
+ Self::AddressNotFound => {
+ AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
+ },
+ Self::GenericNotFoundError { message } => {
+ AER::NotFound(ApiError::new("HE", 5, message, None))
+ },
+ Self::ApiKeyNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
+ }
+ Self::NotSupported { message } => {
+ AER::BadRequest(ApiError::new("HE", 3, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
+ },
+ Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)),
+ Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
+ Self::FlowNotSupported { flow, connector } => {
+ AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
+ }
+ Self::DisputeNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None))
+ }
+ Self::FileNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None))
+ }
+ Self::FileNotAvailable => {
+ AER::NotFound(ApiError::new("HE", 2, "File not available", None))
+ }
+ Self::DisputeStatusValidationFailed { .. } => {
+ AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None))
+ }
+ Self::FileValidationFailed { reason } => {
+ AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None))
+ }
+ Self::MissingFile => {
+ AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None))
+ }
+ Self::MissingFilePurpose => {
+ AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None))
+ }
+ Self::MissingFileContentType => {
+ AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None))
+ }
+ Self::MissingDisputeId => {
+ AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None))
+ }
+ Self::WebhookAuthenticationFailed => {
+ AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
+ }
+ Self::WebhookResourceNotFound => {
+ AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
+ }
+ Self::WebhookBadRequest => {
+ AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
+ }
+ Self::WebhookProcessingFailure => {
+ AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
+ },
+ Self::IncorrectPaymentMethodConfiguration => {
+ AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None))
+ }
+ Self::WebhookUnprocessableEntity => {
+ AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
+ }
+ }
+ }
+}
+
+impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
+ fn switch(&self) -> ApiErrorResponse {
+ match self {
+ Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
+ Self::WebhookSignatureNotFound
+ | Self::WebhookReferenceIdNotFound
+ | Self::WebhookResourceObjectNotFound
+ | Self::WebhookBodyDecodingFailed
+ | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
+ Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
+ _ => ApiErrorResponse::InternalServerError,
+ }
+ }
+}
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 7cf8dc9c3f0..6ab62632e0f 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -1,10 +1,10 @@
pub mod types;
pub mod utils;
+use common_utils::errors::ReportSwitchExt;
use error_stack::{report, IntoReport, ResultExt};
use masking::ExposeInterface;
use router_env::{instrument, tracing};
-use utils::WebhookApiErrorSwitch;
use super::{errors::StorageErrorExt, metrics};
use crate::{
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 35bca6c30c0..5826216b16b 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -1,7 +1,4 @@
-use error_stack::ResultExt;
-
use crate::{
- core::errors,
db::{get_and_deserialize_key, StorageInterface},
types::api,
};
@@ -48,34 +45,3 @@ pub async fn lookup_webhook_event(
}
}
}
-
-pub trait WebhookApiErrorSwitch<T> {
- fn switch(self) -> errors::RouterResult<T>;
-}
-
-impl<T> WebhookApiErrorSwitch<T> for errors::CustomResult<T, errors::ConnectorError> {
- fn switch(self) -> errors::RouterResult<T> {
- match self {
- Ok(res) => Ok(res),
- Err(e) => match e.current_context() {
- errors::ConnectorError::WebhookSourceVerificationFailed => {
- Err(e).change_context(errors::ApiErrorResponse::WebhookAuthenticationFailed)
- }
-
- errors::ConnectorError::WebhookSignatureNotFound
- | errors::ConnectorError::WebhookReferenceIdNotFound
- | errors::ConnectorError::WebhookResourceObjectNotFound
- | errors::ConnectorError::WebhookBodyDecodingFailed
- | errors::ConnectorError::WebhooksNotImplemented => {
- Err(e).change_context(errors::ApiErrorResponse::WebhookBadRequest)
- }
-
- errors::ConnectorError::WebhookEventTypeNotFound => {
- Err(e).change_context(errors::ApiErrorResponse::WebhookUnprocessableEntity)
- }
-
- _ => Err(e).change_context(errors::ApiErrorResponse::InternalServerError),
- },
- }
- }
-}
|
refactor
|
remove `WebhookApiErrorSwitch ` and implement error mapping using `ErrorSwitch` (#1660)
|
049fcdb3fb19c6af45392a5ef3a0cbf642598af8
|
2025-02-21 23:14:11
|
Sarthak Soni
|
fix(routing): Fixed 5xx error logs in dynamic routing metrics (#7335)
| false
|
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 6a21dddc066..b8a7ee5dc1c 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -727,225 +727,231 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
- let success_based_algo_ref = dynamic_routing_algo_ref
- .success_based_algorithm
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?;
-
- if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
- let client = state
- .grpc_client
- .dynamic_routing
- .success_rate_client
- .as_ref()
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
- message: "success_rate gRPC client not found".to_string(),
- })?;
-
- let payment_connector = &payment_attempt.connector.clone().ok_or(
- errors::ApiErrorResponse::GenericNotFoundError {
- message: "unable to derive payment connector from payment attempt".to_string(),
- },
- )?;
-
- let success_based_routing_configs =
- fetch_dynamic_routing_configs::<routing_types::SuccessBasedRoutingConfig>(
+ if let Some(success_based_algo_ref) = dynamic_routing_algo_ref.success_based_algorithm {
+ if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .success_rate_client
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "success_rate gRPC client not found".to_string(),
+ })?;
+
+ let payment_connector = &payment_attempt.connector.clone().ok_or(
+ errors::ApiErrorResponse::GenericNotFoundError {
+ message: "unable to derive payment connector from payment attempt".to_string(),
+ },
+ )?;
+
+ let success_based_routing_configs = fetch_dynamic_routing_configs::<
+ routing_types::SuccessBasedRoutingConfig,
+ >(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
- .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "success_rate algorithm_id not found".to_string(),
+ })
.attach_printable(
"success_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "success_rate based dynamic routing configs not found".to_string(),
+ })
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
- let success_based_routing_config_params = dynamic_routing_config_params_interpolator
- .get_string_val(
- success_based_routing_configs
- .params
- .as_ref()
- .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- );
+ let success_based_routing_config_params = dynamic_routing_config_params_interpolator
+ .get_string_val(
+ success_based_routing_configs
+ .params
+ .as_ref()
+ .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ );
- let success_based_connectors = client
- .calculate_entity_and_global_success_rate(
- profile_id.get_string_repr().into(),
- success_based_routing_configs.clone(),
- success_based_routing_config_params.clone(),
- routable_connectors.clone(),
- state.get_grpc_headers(),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to calculate/fetch success rate from dynamic routing service",
- )?;
+ let success_based_connectors = client
+ .calculate_entity_and_global_success_rate(
+ profile_id.get_string_repr().into(),
+ success_based_routing_configs.clone(),
+ success_based_routing_config_params.clone(),
+ routable_connectors.clone(),
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to calculate/fetch success rate from dynamic routing service",
+ )?;
- let payment_status_attribute =
- get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
+ let payment_status_attribute =
+ get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
- let first_merchant_success_based_connector = &success_based_connectors
- .entity_scores_with_labels
- .first()
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
- )?;
+ let first_merchant_success_based_connector = &success_based_connectors
+ .entity_scores_with_labels
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
+ )?;
- let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
- .split_once(':')
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(format!(
- "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
- first_merchant_success_based_connector.label
- ))?;
-
- let first_global_success_based_connector = &success_based_connectors
- .global_scores_with_labels
- .first()
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
- )?;
+ let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
+ .split_once(':')
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
+ first_merchant_success_based_connector.label
+ ))?;
+
+ let first_global_success_based_connector = &success_based_connectors
+ .global_scores_with_labels
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
+ )?;
- let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
- payment_status_attribute,
- payment_connector.to_string(),
- first_merchant_success_based_connector_label.to_string(),
- );
-
- let dynamic_routing_stats = DynamicRoutingStatsNew {
- payment_id: payment_attempt.payment_id.to_owned(),
- attempt_id: payment_attempt.attempt_id.clone(),
- merchant_id: payment_attempt.merchant_id.to_owned(),
- profile_id: payment_attempt.profile_id.to_owned(),
- amount: payment_attempt.get_total_amount(),
- success_based_routing_connector: first_merchant_success_based_connector_label
- .to_string(),
- payment_connector: payment_connector.to_string(),
- payment_method_type: payment_attempt.payment_method_type,
- currency: payment_attempt.currency,
- payment_method: payment_attempt.payment_method,
- capture_method: payment_attempt.capture_method,
- authentication_type: payment_attempt.authentication_type,
- payment_status: payment_attempt.status,
- conclusive_classification: outcome,
- created_at: common_utils::date_time::now(),
- global_success_based_connector: Some(
- first_global_success_based_connector.label.to_string(),
- ),
- };
+ let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
+ payment_status_attribute,
+ payment_connector.to_string(),
+ first_merchant_success_based_connector_label.to_string(),
+ );
- core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
- 1,
- router_env::metric_attributes!(
- (
- "tenant",
- state.tenant.tenant_id.get_string_repr().to_owned(),
- ),
- (
- "merchant_profile_id",
- format!(
- "{}:{}",
- payment_attempt.merchant_id.get_string_repr(),
- payment_attempt.profile_id.get_string_repr()
- ),
- ),
- (
- "merchant_specific_success_based_routing_connector",
- first_merchant_success_based_connector_label.to_string(),
- ),
- (
- "merchant_specific_success_based_routing_connector_score",
- first_merchant_success_based_connector.score.to_string(),
- ),
- (
- "global_success_based_routing_connector",
+ let dynamic_routing_stats = DynamicRoutingStatsNew {
+ payment_id: payment_attempt.payment_id.to_owned(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ merchant_id: payment_attempt.merchant_id.to_owned(),
+ profile_id: payment_attempt.profile_id.to_owned(),
+ amount: payment_attempt.get_total_amount(),
+ success_based_routing_connector: first_merchant_success_based_connector_label
+ .to_string(),
+ payment_connector: payment_connector.to_string(),
+ payment_method_type: payment_attempt.payment_method_type,
+ currency: payment_attempt.currency,
+ payment_method: payment_attempt.payment_method,
+ capture_method: payment_attempt.capture_method,
+ authentication_type: payment_attempt.authentication_type,
+ payment_status: payment_attempt.status,
+ conclusive_classification: outcome,
+ created_at: common_utils::date_time::now(),
+ global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
- (
- "global_success_based_routing_connector_score",
- first_global_success_based_connector.score.to_string(),
- ),
- ("payment_connector", payment_connector.to_string()),
- (
- "currency",
- payment_attempt
- .currency
- .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
- ),
- (
- "payment_method",
- payment_attempt.payment_method.map_or_else(
- || "None".to_string(),
- |payment_method| payment_method.to_string(),
+ };
+
+ core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
+ 1,
+ router_env::metric_attributes!(
+ (
+ "tenant",
+ state.tenant.tenant_id.get_string_repr().to_owned(),
),
- ),
- (
- "payment_method_type",
- payment_attempt.payment_method_type.map_or_else(
- || "None".to_string(),
- |payment_method_type| payment_method_type.to_string(),
+ (
+ "merchant_profile_id",
+ format!(
+ "{}:{}",
+ payment_attempt.merchant_id.get_string_repr(),
+ payment_attempt.profile_id.get_string_repr()
+ ),
),
- ),
- (
- "capture_method",
- payment_attempt.capture_method.map_or_else(
- || "None".to_string(),
- |capture_method| capture_method.to_string(),
+ (
+ "merchant_specific_success_based_routing_connector",
+ first_merchant_success_based_connector_label.to_string(),
),
- ),
- (
- "authentication_type",
- payment_attempt.authentication_type.map_or_else(
- || "None".to_string(),
- |authentication_type| authentication_type.to_string(),
+ (
+ "merchant_specific_success_based_routing_connector_score",
+ first_merchant_success_based_connector.score.to_string(),
+ ),
+ (
+ "global_success_based_routing_connector",
+ first_global_success_based_connector.label.to_string(),
+ ),
+ (
+ "global_success_based_routing_connector_score",
+ first_global_success_based_connector.score.to_string(),
+ ),
+ ("payment_connector", payment_connector.to_string()),
+ (
+ "currency",
+ payment_attempt
+ .currency
+ .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
+ ),
+ (
+ "payment_method",
+ payment_attempt.payment_method.map_or_else(
+ || "None".to_string(),
+ |payment_method| payment_method.to_string(),
+ ),
+ ),
+ (
+ "payment_method_type",
+ payment_attempt.payment_method_type.map_or_else(
+ || "None".to_string(),
+ |payment_method_type| payment_method_type.to_string(),
+ ),
+ ),
+ (
+ "capture_method",
+ payment_attempt.capture_method.map_or_else(
+ || "None".to_string(),
+ |capture_method| capture_method.to_string(),
+ ),
),
+ (
+ "authentication_type",
+ payment_attempt.authentication_type.map_or_else(
+ || "None".to_string(),
+ |authentication_type| authentication_type.to_string(),
+ ),
+ ),
+ ("payment_status", payment_attempt.status.to_string()),
+ ("conclusive_classification", outcome.to_string()),
),
- ("payment_status", payment_attempt.status.to_string()),
- ("conclusive_classification", outcome.to_string()),
- ),
- );
- logger::debug!("successfully pushed success_based_routing metrics");
-
- state
- .store
- .insert_dynamic_routing_stat_entry(dynamic_routing_stats)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to push dynamic routing stats to db")?;
-
- client
- .update_success_rate(
- profile_id.get_string_repr().into(),
- success_based_routing_configs,
- success_based_routing_config_params,
- vec![routing_types::RoutableConnectorChoiceWithStatus::new(
- routing_types::RoutableConnectorChoice {
- choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
- connector: common_enums::RoutableConnectors::from_str(
- payment_connector.as_str(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to infer routable_connector from connector")?,
- merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
- },
- payment_status_attribute == common_enums::AttemptStatus::Charged,
- )],
- state.get_grpc_headers(),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to update success based routing window in dynamic routing service",
- )?;
- Ok(())
+ );
+ logger::debug!("successfully pushed success_based_routing metrics");
+
+ state
+ .store
+ .insert_dynamic_routing_stat_entry(dynamic_routing_stats)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to push dynamic routing stats to db")?;
+
+ client
+ .update_success_rate(
+ profile_id.get_string_repr().into(),
+ success_based_routing_configs,
+ success_based_routing_config_params,
+ vec![routing_types::RoutableConnectorChoiceWithStatus::new(
+ routing_types::RoutableConnectorChoice {
+ choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
+ connector: common_enums::RoutableConnectors::from_str(
+ payment_connector.as_str(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to infer routable_connector from connector",
+ )?,
+ merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ },
+ payment_status_attribute == common_enums::AttemptStatus::Charged,
+ )],
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to update success based routing window in dynamic routing service",
+ )?;
+ Ok(())
+ } else {
+ Ok(())
+ }
} else {
Ok(())
}
@@ -962,194 +968,205 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing(
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
_dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
- let contract_routing_algo_ref = dynamic_routing_algo_ref
- .contract_based_routing
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table")?;
-
- if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
- let client = state
- .grpc_client
- .dynamic_routing
- .contract_based_client
- .clone()
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
- message: "contract_routing gRPC client not found".to_string(),
- })?;
-
- let payment_connector = &payment_attempt.connector.clone().ok_or(
- errors::ApiErrorResponse::GenericNotFoundError {
- message: "unable to derive payment connector from payment attempt".to_string(),
- },
- )?;
-
- let contract_based_routing_config =
- fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(
- state,
- profile_id,
- contract_routing_algo_ref
- .algorithm_id_with_timestamp
- .algorithm_id
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "contract_based_routing_algorithm_id not found in business_profile",
- )?,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to retrieve contract based dynamic routing configs")?;
-
- let mut existing_label_info = None;
+ if let Some(contract_routing_algo_ref) = dynamic_routing_algo_ref.contract_based_routing {
+ if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None
+ {
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .contract_based_client
+ .clone()
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "contract_routing gRPC client not found".to_string(),
+ })?;
+
+ let payment_connector = &payment_attempt.connector.clone().ok_or(
+ errors::ApiErrorResponse::GenericNotFoundError {
+ message: "unable to derive payment connector from payment attempt".to_string(),
+ },
+ )?;
- contract_based_routing_config
- .label_info
- .as_ref()
- .map(|label_info_vec| {
- for label_info in label_info_vec {
- if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {
- existing_label_info = Some(label_info.clone());
+ let contract_based_routing_config =
+ fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(
+ state,
+ profile_id,
+ contract_routing_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "contract_routing algorithm_id not found".to_string(),
+ })
+ .attach_printable(
+ "contract_based_routing_algorithm_id not found in business_profile",
+ )?,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "contract based dynamic routing configs not found".to_string(),
+ })
+ .attach_printable("unable to retrieve contract based dynamic routing configs")?;
+
+ let mut existing_label_info = None;
+
+ contract_based_routing_config
+ .label_info
+ .as_ref()
+ .map(|label_info_vec| {
+ for label_info in label_info_vec {
+ if Some(&label_info.mca_id)
+ == payment_attempt.merchant_connector_id.as_ref()
+ {
+ existing_label_info = Some(label_info.clone());
+ }
}
- }
- });
-
- let final_label_info = existing_label_info
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to get LabelInformation from ContractBasedRoutingConfig")?;
-
- logger::debug!(
- "contract based routing: matched LabelInformation - {:?}",
- final_label_info
- );
-
- let request_label_info = routing_types::LabelInformation {
- label: format!(
- "{}:{}",
- final_label_info.label.clone(),
- final_label_info.mca_id.get_string_repr()
- ),
- target_count: final_label_info.target_count,
- target_time: final_label_info.target_time,
- mca_id: final_label_info.mca_id.to_owned(),
- };
+ });
- let payment_status_attribute =
- get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
+ let final_label_info = existing_label_info
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "LabelInformation from ContractBasedRoutingConfig not found"
+ .to_string(),
+ })
+ .attach_printable(
+ "unable to get LabelInformation from ContractBasedRoutingConfig",
+ )?;
- if payment_status_attribute == common_enums::AttemptStatus::Charged {
- client
- .update_contracts(
+ logger::debug!(
+ "contract based routing: matched LabelInformation - {:?}",
+ final_label_info
+ );
+
+ let request_label_info = routing_types::LabelInformation {
+ label: format!(
+ "{}:{}",
+ final_label_info.label.clone(),
+ final_label_info.mca_id.get_string_repr()
+ ),
+ target_count: final_label_info.target_count,
+ target_time: final_label_info.target_time,
+ mca_id: final_label_info.mca_id.to_owned(),
+ };
+
+ let payment_status_attribute =
+ get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
+
+ if payment_status_attribute == common_enums::AttemptStatus::Charged {
+ client
+ .update_contracts(
+ profile_id.get_string_repr().into(),
+ vec![request_label_info],
+ "".to_string(),
+ vec![],
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to update contract based routing window in dynamic routing service",
+ )?;
+ }
+
+ let contract_scores = client
+ .calculate_contract_score(
profile_id.get_string_repr().into(),
- vec![request_label_info],
+ contract_based_routing_config.clone(),
"".to_string(),
- vec![],
+ routable_connectors.clone(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
- "unable to update contract based routing window in dynamic routing service",
+ "unable to calculate/fetch contract scores from dynamic routing service",
)?;
- }
- let contract_scores = client
- .calculate_contract_score(
- profile_id.get_string_repr().into(),
- contract_based_routing_config.clone(),
- "".to_string(),
- routable_connectors.clone(),
- state.get_grpc_headers(),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to calculate/fetch contract scores from dynamic routing service",
- )?;
-
- let first_contract_based_connector = &contract_scores
- .labels_with_score
- .first()
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
- )?;
+ let first_contract_based_connector = &contract_scores
+ .labels_with_score
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
+ )?;
- let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label
- .split_once(':')
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(format!(
- "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
- first_contract_based_connector
- ))?
- .0, first_contract_based_connector.score, first_contract_based_connector.current_count );
-
- core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(
- 1,
- router_env::metric_attributes!(
- (
- "tenant",
- state.tenant.tenant_id.get_string_repr().to_owned(),
- ),
- (
- "merchant_profile_id",
- format!(
- "{}:{}",
- payment_attempt.merchant_id.get_string_repr(),
- payment_attempt.profile_id.get_string_repr()
+ let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label
+ .split_once(':')
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
+ first_contract_based_connector
+ ))?
+ .0, first_contract_based_connector.score, first_contract_based_connector.current_count );
+
+ core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(
+ 1,
+ router_env::metric_attributes!(
+ (
+ "tenant",
+ state.tenant.tenant_id.get_string_repr().to_owned(),
),
- ),
- (
- "contract_based_routing_connector",
- first_contract_based_connector.to_string(),
- ),
- (
- "contract_based_routing_connector_score",
- connector_score.to_string(),
- ),
- (
- "current_payment_count_contract_based_routing_connector",
- current_payment_cnt.to_string(),
- ),
- ("payment_connector", payment_connector.to_string()),
- (
- "currency",
- payment_attempt
- .currency
- .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
- ),
- (
- "payment_method",
- payment_attempt.payment_method.map_or_else(
- || "None".to_string(),
- |payment_method| payment_method.to_string(),
+ (
+ "merchant_profile_id",
+ format!(
+ "{}:{}",
+ payment_attempt.merchant_id.get_string_repr(),
+ payment_attempt.profile_id.get_string_repr()
+ ),
),
- ),
- (
- "payment_method_type",
- payment_attempt.payment_method_type.map_or_else(
- || "None".to_string(),
- |payment_method_type| payment_method_type.to_string(),
+ (
+ "contract_based_routing_connector",
+ first_contract_based_connector.to_string(),
),
- ),
- (
- "capture_method",
- payment_attempt.capture_method.map_or_else(
- || "None".to_string(),
- |capture_method| capture_method.to_string(),
+ (
+ "contract_based_routing_connector_score",
+ connector_score.to_string(),
),
- ),
- (
- "authentication_type",
- payment_attempt.authentication_type.map_or_else(
- || "None".to_string(),
- |authentication_type| authentication_type.to_string(),
+ (
+ "current_payment_count_contract_based_routing_connector",
+ current_payment_cnt.to_string(),
+ ),
+ ("payment_connector", payment_connector.to_string()),
+ (
+ "currency",
+ payment_attempt
+ .currency
+ .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
+ (
+ "payment_method",
+ payment_attempt.payment_method.map_or_else(
+ || "None".to_string(),
+ |payment_method| payment_method.to_string(),
+ ),
+ ),
+ (
+ "payment_method_type",
+ payment_attempt.payment_method_type.map_or_else(
+ || "None".to_string(),
+ |payment_method_type| payment_method_type.to_string(),
+ ),
+ ),
+ (
+ "capture_method",
+ payment_attempt.capture_method.map_or_else(
+ || "None".to_string(),
+ |capture_method| capture_method.to_string(),
+ ),
+ ),
+ (
+ "authentication_type",
+ payment_attempt.authentication_type.map_or_else(
+ || "None".to_string(),
+ |authentication_type| authentication_type.to_string(),
+ ),
+ ),
+ ("payment_status", payment_attempt.status.to_string()),
),
- ("payment_status", payment_attempt.status.to_string()),
- ),
- );
- logger::debug!("successfully pushed contract_based_routing metrics");
+ );
+ logger::debug!("successfully pushed contract_based_routing metrics");
- Ok(())
+ Ok(())
+ } else {
+ Ok(())
+ }
} else {
Ok(())
}
|
fix
|
Fixed 5xx error logs in dynamic routing metrics (#7335)
|
20bea23b75c30b27f5beda78ac2ffa8302c6e6a8
|
2023-04-25 01:06:12
|
Shankar Singh C
|
feat(connector): add 3ds for Bambora and Support Html 3ds response (#817)
| false
|
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index de5932fe63b..570ad607f0c 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1324,7 +1324,7 @@ pub fn get_redirection_response(
.map(|(key, value)| (key.to_string(), value.to_string())),
)
});
- services::RedirectForm {
+ services::RedirectForm::Form {
endpoint: url.to_string(),
method: response.action.method.unwrap_or(services::Method::Get),
form_fields,
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index c71f2ead3ad..9283c7eb703 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -150,7 +150,7 @@ pub struct AirwallexCompleteRequest {
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexThreeDsData {
- acs_response: Option<common_utils::pii::SecretSerdeValue>,
+ acs_response: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -166,7 +166,11 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for AirwallexCompleteR
Ok(Self {
request_id: Uuid::new_v4().to_string(),
three_ds: AirwallexThreeDsData {
- acs_response: item.request.payload.clone().map(Secret::new),
+ acs_response: item
+ .request
+ .payload
+ .as_ref()
+ .map(|data| Secret::new(serde_json::Value::to_string(data))),
},
three_ds_type: AirwallexThreeDsType::ThreeDSContinue,
})
@@ -285,7 +289,7 @@ pub struct AirwallexPaymentsResponse {
fn get_redirection_form(
response_url_data: AirwallexPaymentsNextAction,
) -> Option<services::RedirectForm> {
- Some(services::RedirectForm {
+ Some(services::RedirectForm::Form {
endpoint: response_url_data.url.to_string(),
method: response_url_data.method,
form_fields: std::collections::HashMap::from([
diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index 59d816899ea..984134f46ba 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -8,8 +8,11 @@ use transformers as bambora;
use super::utils::RefundsRequestData;
use crate::{
configs::settings,
- connector::utils::{PaymentsAuthorizeRequestData, PaymentsSyncRequestData},
- core::errors::{self, CustomResult},
+ connector::utils::{to_connector_meta, PaymentsAuthorizeRequestData, PaymentsSyncRequestData},
+ core::{
+ errors::{self, CustomResult},
+ payments,
+ },
headers, logger,
services::{self, ConnectorIntegration},
types::{
@@ -166,7 +169,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
data: &types::PaymentsCancelRouterData,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
- let response: bambora::BamboraPaymentsResponse = res
+ let response: bambora::BamboraResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -257,7 +260,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
data: &types::PaymentsSyncRouterData,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: bambora::BamboraPaymentsResponse = res
+ let response: bambora::BamboraResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -336,7 +339,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
data: &types::PaymentsCaptureRouterData,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: bambora::BamboraPaymentsResponse = res
+ let response: bambora::BamboraResponse = res
.response
.parse_struct("Bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -388,9 +391,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> {
- Ok(format!("{}{}", self.base_url(_connectors), "/v1/payments"))
+ Ok(format!("{}{}", self.base_url(connectors), "/v1/payments"))
}
fn get_request_body(
@@ -429,7 +432,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
data: &types::PaymentsAuthorizeRouterData,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: bambora::BamboraPaymentsResponse = res
+ let response: bambora::BamboraResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -638,3 +641,111 @@ pub fn get_payment_flow(is_auto_capture: bool) -> bambora::PaymentFlow {
bambora::PaymentFlow::Authorize
}
}
+
+impl services::ConnectorRedirectResponse for Bambora {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ _action: services::PaymentAction,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+}
+
+impl api::PaymentsCompleteAuthorize for Bambora {}
+
+impl
+ ConnectorIntegration<
+ api::CompleteAuthorize,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ > for Bambora
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let meta: bambora::BamboraMeta = to_connector_meta(req.request.connector_meta.clone())?;
+ Ok(format!(
+ "{}/v1/payments/{}{}",
+ self.base_url(connectors),
+ meta.three_d_session_data,
+ "/continue"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let request = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?;
+ let bambora_req =
+ utils::Encode::<bambora::BamboraThreedsContinueRequest>::encode_to_string_of_json(
+ &request,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bambora_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ self, req,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCompleteAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ let response: bambora::BamboraResponse = res
+ .response
+ .parse_struct("Bambora PaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(bamborapayments_create_response=?response);
+ types::RouterData::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ bambora::PaymentFlow::Capture,
+ ))
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index f9dbf97f191..70f6d231a01 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -1,4 +1,6 @@
use base64::Engine;
+use common_utils::ext_traits::ValueExt;
+use error_stack::{IntoReport, ResultExt};
use masking::Secret;
use serde::{Deserialize, Deserializer, Serialize};
@@ -6,6 +8,7 @@ use crate::{
connector::utils::PaymentsAuthorizeRequestData,
consts,
core::errors,
+ services,
types::{self, api, storage::enums},
};
@@ -24,19 +27,21 @@ pub struct BamboraCard {
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ThreeDSecure {
- // browser: Option<Browser>, //Needed only in case of 3Ds 2.0. Need to update request for this.
+ browser: Option<BamboraBrowserInfo>, //Needed only in case of 3Ds 2.0. Need to update request for this.
enabled: bool,
+ version: Option<i64>,
+ auth_required: Option<bool>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct Browser {
+pub struct BamboraBrowserInfo {
accept_header: String,
- java_enabled: String,
+ java_enabled: bool,
language: String,
- color_depth: String,
- screen_height: i64,
- screen_width: i64,
- time_zone: i64,
+ color_depth: u8,
+ screen_height: u32,
+ screen_width: u32,
+ time_zone: i32,
user_agent: String,
javascript_enabled: bool,
}
@@ -45,16 +50,63 @@ pub struct Browser {
pub struct BamboraPaymentsRequest {
amount: i64,
payment_method: PaymentMethod,
+ customer_ip: Option<std::net::IpAddr>,
+ term_url: Option<String>,
card: BamboraCard,
}
+fn get_browser_info(item: &types::PaymentsAuthorizeRouterData) -> Option<BamboraBrowserInfo> {
+ if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) {
+ item.request
+ .browser_info
+ .as_ref()
+ .map(|info| BamboraBrowserInfo {
+ accept_header: info.accept_header.clone(),
+ java_enabled: info.java_enabled,
+ language: info.language.clone(),
+ color_depth: info.color_depth,
+ screen_height: info.screen_height,
+ screen_width: info.screen_width,
+ time_zone: info.time_zone,
+ user_agent: info.user_agent.clone(),
+ javascript_enabled: info.java_script_enabled,
+ })
+ } else {
+ None
+ }
+}
+
+impl TryFrom<&types::CompleteAuthorizeData> for BamboraThreedsContinueRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(value: &types::CompleteAuthorizeData) -> Result<Self, Self::Error> {
+ let card_response: CardResponse = value
+ .payload
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "payload",
+ })?
+ .parse_value("CardResponse")
+ .change_context(errors::ConnectorError::ParsingFailed)?;
+ let bambora_req = Self {
+ payment_method: "credit_card".to_string(),
+ card_response,
+ };
+ Ok(bambora_req)
+ }
+}
+
impl TryFrom<&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() {
api::PaymentMethodData::Card(req_card) => {
let three_ds = match item.auth_type {
- enums::AuthenticationType::ThreeDs => Some(ThreeDSecure { enabled: true }),
+ enums::AuthenticationType::ThreeDs => Some(ThreeDSecure {
+ enabled: true,
+ browser: get_browser_info(item),
+ version: Some(2),
+ auth_required: Some(true),
+ }),
enums::AuthenticationType::NoThreeDs => None,
};
let bambora_card = BamboraCard {
@@ -66,10 +118,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
three_d_secure: three_ds,
complete: item.request.is_auto_capture()?,
};
+ let browser_info = item.request.get_browser_info()?;
Ok(Self {
amount: item.request.amount,
payment_method: PaymentMethod::Card,
card: bambora_card,
+ customer_ip: browser_info.ip_address,
+ term_url: item.request.complete_authorize_url.clone(),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
@@ -115,42 +170,68 @@ pub enum PaymentFlow {
// PaymentsResponse
impl<F, T>
TryFrom<(
- types::ResponseRouterData<F, BamboraPaymentsResponse, T, types::PaymentsResponseData>,
+ types::ResponseRouterData<F, BamboraResponse, T, types::PaymentsResponseData>,
PaymentFlow,
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
data: (
- types::ResponseRouterData<F, BamboraPaymentsResponse, T, types::PaymentsResponseData>,
+ types::ResponseRouterData<F, BamboraResponse, T, types::PaymentsResponseData>,
PaymentFlow,
),
) -> Result<Self, Self::Error> {
let flow = data.1;
let item = data.0;
- let pg_response = item.response;
- Ok(Self {
- status: match pg_response.approved.as_str() {
- "0" => match flow {
- PaymentFlow::Authorize => enums::AttemptStatus::AuthorizationFailed,
- PaymentFlow::Capture => enums::AttemptStatus::Failure,
- PaymentFlow::Void => enums::AttemptStatus::VoidFailed,
- },
- "1" => match flow {
- PaymentFlow::Authorize => enums::AttemptStatus::Authorized,
- PaymentFlow::Capture => enums::AttemptStatus::Charged,
- PaymentFlow::Void => enums::AttemptStatus::Voided,
+ match item.response {
+ BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
+ status: match pg_response.approved.as_str() {
+ "0" => match flow {
+ PaymentFlow::Authorize => enums::AttemptStatus::AuthorizationFailed,
+ PaymentFlow::Capture => enums::AttemptStatus::Failure,
+ PaymentFlow::Void => enums::AttemptStatus::VoidFailed,
+ },
+ "1" => match flow {
+ PaymentFlow::Authorize => enums::AttemptStatus::Authorized,
+ PaymentFlow::Capture => enums::AttemptStatus::Charged,
+ PaymentFlow::Void => enums::AttemptStatus::Voided,
+ },
+ &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
},
- &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
- },
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(pg_response.id.to_string()),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ pg_response.id.to_string(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ }),
+ ..item.data
}),
- ..item.data
- })
+
+ BamboraResponse::ThreeDsResponse(response) => {
+ let value = url::form_urlencoded::parse(response.contents.as_bytes())
+ .map(|(key, val)| [key, val].concat())
+ .collect();
+ let redirection_data = Some(services::RedirectForm::Html { html_data: value });
+ Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata: Some(
+ serde_json::to_value(BamboraMeta {
+ three_d_session_data: response.three_d_session_data,
+ })
+ .into_report()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?,
+ ),
+ }),
+ ..item.data
+ })
+ }
+ }
}
}
@@ -173,7 +254,14 @@ where
Ok(res)
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize)]
+#[serde(untagged)]
+pub enum BamboraResponse {
+ NormalTransaction(Box<BamboraPaymentsResponse>),
+ ThreeDsResponse(Box<Bambora3DsResponse>),
+}
+
+#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
pub struct BamboraPaymentsResponse {
#[serde(deserialize_with = "str_or_i32")]
id: String,
@@ -203,7 +291,30 @@ pub struct BamboraPaymentsResponse {
risk_score: Option<f32>,
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize)]
+pub struct Bambora3DsResponse {
+ #[serde(rename = "3d_session_data")]
+ three_d_session_data: String,
+ contents: String,
+}
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+pub struct BamboraMeta {
+ pub three_d_session_data: String,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct BamboraThreedsContinueRequest {
+ pub(crate) payment_method: String,
+ pub card_response: CardResponse,
+}
+
+#[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)]
+pub struct CardResponse {
+ pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>,
+}
+
+#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
pub struct CardData {
name: Option<String>,
expiry_month: Option<String>,
@@ -337,34 +448,34 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize)]
pub struct RefundResponse {
#[serde(deserialize_with = "str_or_i32")]
- id: String,
- authorizing_merchant_id: i32,
+ pub id: String,
+ pub authorizing_merchant_id: i32,
#[serde(deserialize_with = "str_or_i32")]
- approved: String,
+ pub approved: String,
#[serde(deserialize_with = "str_or_i32")]
- message_id: String,
- message: String,
- auth_code: String,
- created: String,
- amount: f32,
- order_number: String,
+ pub message_id: String,
+ pub message: String,
+ pub auth_code: String,
+ pub created: String,
+ pub amount: f32,
+ pub order_number: String,
#[serde(rename = "type")]
- payment_type: String,
- comments: Option<String>,
- batch_number: Option<String>,
- total_refunds: Option<f32>,
- total_completions: Option<f32>,
- payment_method: String,
- card: CardData,
- billing: Option<AddressData>,
- shipping: Option<AddressData>,
- custom: CustomData,
- adjusted_by: Option<Vec<AdjustedBy>>,
- links: Vec<Links>,
- risk_score: Option<f32>,
+ pub payment_type: String,
+ pub comments: Option<String>,
+ pub batch_number: Option<String>,
+ pub total_refunds: Option<f32>,
+ pub total_completions: Option<f32>,
+ pub payment_method: String,
+ pub card: CardData,
+ pub billing: Option<AddressData>,
+ pub shipping: Option<AddressData>,
+ pub custom: CustomData,
+ pub adjusted_by: Option<Vec<AdjustedBy>>,
+ pub links: Vec<Links>,
+ pub risk_score: Option<f32>,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs
index fcd8cd24b28..627ae4dadda 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/router/src/connector/coinbase/transformers.rs
@@ -124,7 +124,7 @@ impl<F, T>
>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm {
+ let redirection_data = services::RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
method: services::Method::Get,
form_fields,
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 2d125818b70..2207cac17ed 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1121,7 +1121,7 @@ where
.and_then(|o| o.card.clone())
.and_then(|card| card.three_d)
.and_then(|three_ds| three_ds.acs_url.zip(three_ds.c_req))
- .map(|(base_url, creq)| services::RedirectForm {
+ .map(|(base_url, creq)| services::RedirectForm::Form {
endpoint: base_url,
method: services::Method::Post,
form_fields: std::collections::HashMap::from([("creq".to_string(), creq)]),
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index f951b8eb92c..e2c9e840902 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -97,7 +97,7 @@ impl<F, T>
>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm {
+ let redirection_data = services::RedirectForm::Form {
endpoint: item.response.data.hosted_checkout_url.to_string(),
method: services::Method::Get,
form_fields,
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index f039321070a..ae63a7277a7 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -558,11 +558,13 @@ fn handle_cards_response(
response.redirect_url.clone(),
)?;
let form_fields = response.redirect_params.unwrap_or_default();
- let redirection_data = response.redirect_url.map(|url| services::RedirectForm {
- endpoint: url.to_string(),
- method: services::Method::Post,
- form_fields,
- });
+ let redirection_data = response
+ .redirect_url
+ .map(|url| services::RedirectForm::Form {
+ endpoint: url.to_string(),
+ method: services::Method::Post,
+ form_fields,
+ });
let error = if msg.is_some() {
Some(types::ErrorResponse {
code: response.payment_status,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index f1c50f3e78d..945351994b5 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -89,7 +89,6 @@ default_imp_for_complete_authorize!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bluesnap,
connector::Braintree,
connector::Checkout,
@@ -132,7 +131,6 @@ default_imp_for_connector_redirect_response!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bluesnap,
connector::Braintree,
connector::Coinbase,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index c465f68360f..acbca0f48ca 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -701,7 +701,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
let json_payload = payment_data
.connector_response
.encoded_data
- .map(serde_json::to_value)
+ .map(|s| serde_json::from_str::<serde_json::Value>(&s))
.transpose()
.into_report()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index aa4bdd9c49f..13080cf8ade 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -467,10 +467,15 @@ pub struct ApplicationRedirectResponse {
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
-pub struct RedirectForm {
- pub endpoint: String,
- pub method: Method,
- pub form_fields: HashMap<String, String>,
+pub enum RedirectForm {
+ Form {
+ endpoint: String,
+ method: Method,
+ form_fields: HashMap<String, String>,
+ },
+ Html {
+ html_data: String,
+ },
}
impl From<(url::Url, Method)> for RedirectForm {
@@ -484,7 +489,7 @@ impl From<(url::Url, Method)> for RedirectForm {
// Do not include query params in the endpoint
redirect_url.set_query(None);
- Self {
+ Self::Form {
endpoint: redirect_url.to_string(),
method,
form_fields,
@@ -681,7 +686,12 @@ impl Authenticate for api_models::payment_methods::PaymentMethodListRequest {
pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup {
use maud::PreEscaped;
- maud::html! {
+ match form {
+ RedirectForm::Form {
+ endpoint,
+ method,
+ form_fields,
+ } => maud::html! {
(maud::DOCTYPE)
html {
meta name="viewport" content="width=device-width, initial-scale=1";
@@ -726,8 +736,8 @@ pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup {
h3 style="text-align: center;" { "Please wait while we process your payment..." }
- form action=(PreEscaped(&form.endpoint)) method=(form.method.to_string()) #payment_form {
- @for (field, value) in &form.form_fields {
+ form action=(PreEscaped(endpoint)) method=(method.to_string()) #payment_form {
+ @for (field, value) in form_fields {
input type="hidden" name=(field) value=(value);
}
}
@@ -735,6 +745,8 @@ pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup {
(PreEscaped(r#"<script type="text/javascript"> var frm = document.getElementById("payment_form"); window.setTimeout(function () { frm.submit(); }, 300); </script>"#))
}
}
+ },
+ RedirectForm::Html { html_data } => PreEscaped(html_data.to_string()),
}
}
|
feat
|
add 3ds for Bambora and Support Html 3ds response (#817)
|
ae77373b4cac63979673fdac37c55986d954358e
|
2024-05-23 15:48:51
|
Hrithikesh
|
chore: move RouterData Request types to hyperswitch_domain_models crate (#4723)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 89a0d9d5079..9411c009aef 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3667,18 +3667,25 @@ dependencies = [
name = "hyperswitch_domain_models"
version = "0.1.0"
dependencies = [
+ "actix-web",
"api_models",
"async-trait",
+ "cards",
"common_enums",
"common_utils",
"diesel_models",
"error-stack",
"http 0.2.12",
"masking",
+ "mime",
+ "router_derive",
"serde",
"serde_json",
+ "serde_with",
"thiserror",
"time",
+ "url",
+ "utoipa",
]
[[package]]
@@ -6051,6 +6058,7 @@ dependencies = [
"error-stack",
"external_services",
"futures 0.3.30",
+ "hyperswitch_domain_models",
"masking",
"num_cpus",
"once_cell",
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index dd3335cb2c0..c1db2a4fb99 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -14,17 +14,25 @@ payouts = ["api_models/payouts"]
[dependencies]
# First party deps
-api_models = { version = "0.1.0", path = "../api_models" }
+api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
masking = { version = "0.1.0", path = "../masking" }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
+cards = {version = "0.1.0", path = "../cards"}
+router_derive = {version = "0.1.0", path = "../router_derive"}
# Third party deps
+actix-web = "4.5.1"
async-trait = "0.1.79"
error-stack = "0.4.1"
http = "0.2.12"
+mime = "0.3.17"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
+serde_with = "3.7.0"
thiserror = "1.0.58"
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", "time"] }
+
diff --git a/crates/hyperswitch_domain_models/src/errors.rs b/crates/hyperswitch_domain_models/src/errors.rs
index bed1ab9ccbf..bd05e1a3771 100644
--- a/crates/hyperswitch_domain_models/src/errors.rs
+++ b/crates/hyperswitch_domain_models/src/errors.rs
@@ -1,3 +1,4 @@
+pub mod api_error_response;
use diesel_models::errors::DatabaseError;
pub type StorageResult<T> = error_stack::Result<T, StorageError>;
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
new file mode 100644
index 00000000000..26a6f1618fa
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -0,0 +1,634 @@
+use api_models::errors::types::Extra;
+use common_utils::errors::ErrorSwitch;
+use http::StatusCode;
+
+use crate::router_data;
+
+#[derive(Clone, Debug, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ErrorType {
+ InvalidRequestError,
+ ObjectNotFound,
+ RouterError,
+ ProcessingError,
+ BadGateway,
+ ServerNotAvailable,
+ DuplicateRequest,
+ ValidationError,
+ ConnectorError,
+ LockTimeout,
+}
+
+#[derive(Debug, Clone, router_derive::ApiError)]
+#[error(error_type_enum = ErrorType)]
+pub enum ApiErrorResponse {
+ #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")]
+ NotImplemented { message: NotImplementedMessage },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_01",
+ message = "API key not provided or invalid API key used"
+ )]
+ Unauthorized,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")]
+ InvalidRequestUrl,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")]
+ InvalidHttpMethod,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")]
+ MissingRequiredField { field_name: &'static str },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_05",
+ message = "{field_name} contains invalid data. Expected format is {expected_format}"
+ )]
+ InvalidDataFormat {
+ field_name: String,
+ expected_format: String,
+ },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")]
+ InvalidRequestData { message: String },
+ /// Typically used when a field has invalid value, or deserialization of the value contained in a field fails.
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")]
+ InvalidDataValue { field_name: &'static str },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")]
+ ClientSecretNotGiven,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")]
+ ClientSecretExpired,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")]
+ ClientSecretInvalid,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")]
+ MandateActive,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")]
+ CustomerRedacted,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")]
+ MaximumRefundCount,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")]
+ RefundAmountExceedsPaymentAmount,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")]
+ PaymentUnexpectedState {
+ current_flow: String,
+ field_name: String,
+ current_value: String,
+ states: String,
+ },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]
+ InvalidEphemeralKey,
+ /// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]
+ PreconditionFailed { message: String },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_17",
+ message = "Access forbidden, invalid JWT token was used"
+ )]
+ InvalidJwtToken,
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_18",
+ message = "{message}",
+ )]
+ GenericUnauthorized { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
+ NotSupported { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")]
+ FlowNotSupported { flow: String, connector: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
+ MissingRequiredFields { field_names: Vec<&'static str> },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
+ AccessForbidden { resource: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
+ FileProviderNotSupported { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
+ UnprocessableEntity { message: String },
+ #[error(
+ error_type = ErrorType::ProcessingError, code = "IR_24",
+ message = "Invalid {wallet_name} wallet token"
+ )]
+ InvalidWalletToken { wallet_name: String },
+ #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
+ ExternalConnectorError {
+ code: String,
+ message: String,
+ connector: String,
+ status_code: u16,
+ reason: Option<String>,
+ },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")]
+ PaymentAuthorizationFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")]
+ PaymentAuthenticationFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")]
+ PaymentCaptureFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]
+ InvalidCardData { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "CE_04", message = "Payout validation failed")]
+ PayoutFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]
+ CardExpired { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]
+ RefundFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")]
+ VerificationFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")]
+ DisputeFailed { data: Option<serde_json::Value> },
+ #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]
+ InternalServerError,
+ #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]
+ ResourceBusy,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]
+ DuplicateRefundRequest,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]
+ DuplicateMandate,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
+ DuplicateMerchantAccount,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
+ DuplicateMerchantConnectorAccount {
+ profile_id: String,
+ connector_label: String,
+ },
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
+ DuplicatePaymentMethod,
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")]
+ DuplicatePayment { payment_id: String },
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id}' already exists in our records")]
+ DuplicatePayout { payout_id: String },
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")]
+ DuplicateConfig,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")]
+ RefundNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]
+ CustomerNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Config key does not exist in our records.")]
+ ConfigNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")]
+ PaymentNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")]
+ PaymentMethodNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")]
+ MerchantAccountNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")]
+ MerchantConnectorAccountNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")]
+ BusinessProfileNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")]
+ PollNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")]
+ ResourceIdNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")]
+ MandateNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")]
+ AuthenticationNotFound { id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")]
+ MandateUpdateFailed,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]
+ ApiKeyNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]
+ PayoutNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")]
+ EventNotFound,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]
+ MandateSerializationFailed,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]
+ MandateDeserializationFailed,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")]
+ ReturnUrlUnavailable,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")]
+ RefundNotPossible { connector: String },
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )]
+ MandateValidationFailed { reason: String },
+ #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")]
+ PaymentNotSucceeded,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")]
+ MerchantConnectorAccountDisabled,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")]
+ PaymentBlockedError {
+ code: u16,
+ message: String,
+ status: String,
+ reason: String,
+ },
+ #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")]
+ SuccessfulPaymentNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")]
+ IncorrectConnectorNameGiven,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")]
+ AddressNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")]
+ DisputeNotFound { dispute_id: String },
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")]
+ FileNotFound,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")]
+ FileNotAvailable,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute status validation failed")]
+ DisputeStatusValidationFailed { reason: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Card with the provided iin does not exist")]
+ InvalidCardIin,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")]
+ InvalidCardIinLength,
+ #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")]
+ FileValidationFailed { reason: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File not found / valid in the request")]
+ MissingFile,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute id not found in the request")]
+ MissingDisputeId,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File purpose not found in the request or is invalid")]
+ MissingFilePurpose,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File content type not found / valid")]
+ MissingFileContentType,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_05", message = "{message}")]
+ GenericNotFoundError { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_01", message = "{message}")]
+ GenericDuplicateError { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
+ WebhookAuthenticationFailed,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")]
+ WebhookResourceNotFound,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
+ WebhookBadRequest,
+ #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")]
+ WebhookProcessingFailure,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "required payment method is not configured or configured incorrectly for all configured connectors")]
+ IncorrectPaymentMethodConfiguration,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")]
+ WebhookUnprocessableEntity,
+ #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")]
+ PaymentLinkNotFound,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Merchant Secret set my merchant for webhook source verification is invalid")]
+ WebhookInvalidMerchantSecret,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
+ CurrencyNotSupported { message: String },
+ #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")]
+ HealthCheckError {
+ component: &'static str,
+ message: String,
+ },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_24", message = "Merchant connector account is configured with invalid {config}")]
+ InvalidConnectorConfiguration { config: String },
+ #[error(error_type = ErrorType::ValidationError, code = "HE_01", message = "Failed to convert currency to minor unit")]
+ CurrencyConversionFailed,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
+ PaymentMethodDeleteFailed,
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_26",
+ message = "Invalid Cookie"
+ )]
+ InvalidCookie,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
+ ExtendedCardInfoNotFound,
+}
+
+#[derive(Clone)]
+pub enum NotImplementedMessage {
+ Reason(String),
+ Default,
+}
+
+impl std::fmt::Debug for NotImplementedMessage {
+ fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Reason(message) => write!(fmt, "{message} is not implemented"),
+ Self::Default => {
+ write!(
+ fmt,
+ "This API is under development and will be made available soon."
+ )
+ }
+ }
+ }
+}
+
+impl ::core::fmt::Display for ApiErrorResponse {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ r#"{{"error":{}}}"#,
+ serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
+ )
+ }
+}
+
+impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
+ fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
+ use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
+
+ match self {
+ Self::NotImplemented { message } => {
+ AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
+ }
+ Self::Unauthorized => AER::Unauthorized(ApiError::new(
+ "IR",
+ 1,
+ "API key not provided or invalid API key used", None
+ )),
+ Self::InvalidRequestUrl => {
+ AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
+ }
+ Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
+ "IR",
+ 3,
+ "The HTTP method is not applicable for this API", None
+ )),
+ Self::MissingRequiredField { field_name } => AER::BadRequest(
+ ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
+ ),
+ Self::InvalidDataFormat {
+ field_name,
+ expected_format,
+ } => AER::Unprocessable(ApiError::new(
+ "IR",
+ 5,
+ format!(
+ "{field_name} contains invalid data. Expected format is {expected_format}"
+ ), None
+ )),
+ Self::InvalidRequestData { message } => {
+ AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
+ }
+ Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
+ "IR",
+ 7,
+ format!("Invalid value provided: {field_name}"), None
+ )),
+ Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
+ "IR",
+ 8,
+ "client_secret was not provided", None
+ )),
+ Self::ClientSecretInvalid => {
+ AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
+ }
+ Self::CurrencyNotSupported { message } => {
+ AER::BadRequest(ApiError::new("IR", 9, message, None))
+ }
+ Self::MandateActive => {
+ AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
+ }
+ Self::CustomerRedacted => {
+ AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
+ }
+ Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
+ Self::RefundAmountExceedsPaymentAmount => {
+ AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
+ }
+ Self::PaymentUnexpectedState {
+ current_flow,
+ field_name,
+ current_value,
+ states,
+ } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
+ Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
+ Self::PreconditionFailed { message } => {
+ AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
+ }
+ Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
+ Self::GenericUnauthorized { message } => {
+ AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
+ },
+ Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
+ "IR",
+ 19,
+ "The provided client_secret has expired", None
+ )),
+ Self::MissingRequiredFields { field_names } => AER::BadRequest(
+ ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
+ ),
+ Self::AccessForbidden {resource} => {
+ AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
+ },
+ Self::FileProviderNotSupported { message } => {
+ AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
+ },
+ Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 23, message.to_string(), None)),
+ Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
+ "IR",
+ 24,
+ format!("Invalid {wallet_name} wallet token"), None
+ )),
+ Self::ExternalConnectorError {
+ code,
+ message,
+ connector,
+ reason,
+ status_code,
+ } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned().map(Into::into), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
+ Self::PaymentAuthorizationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::PaymentAuthenticationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::PaymentCaptureFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::DisputeFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
+ }
+ Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
+ Self::VerificationFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
+ },
+ Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {
+ AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
+ },
+ Self::HealthCheckError { message,component } => {
+ AER::InternalServerError(ApiError::new("HE",0,format!("{} health check failed with error: {}",component,message),None))
+ },
+ Self::PayoutFailed { data } => {
+ AER::BadRequest(ApiError::new("CE", 4, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
+ },
+ Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
+ Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
+ Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
+ Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None))
+ }
+ Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
+ Self::DuplicatePayment { payment_id } => {
+ AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id} already exists")), ..Default::default()})))
+ }
+ Self::DuplicatePayout { payout_id } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id}' already exists in our records"), None))
+ }
+ Self::GenericDuplicateError { message } => {
+ AER::BadRequest(ApiError::new("HE", 1, message, None))
+ }
+ Self::RefundNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
+ }
+ Self::CustomerNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
+ }
+ Self::ConfigNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
+ },
+ Self::DuplicateConfig => {
+ AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
+ }
+ Self::PaymentNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
+ }
+ Self::PaymentMethodNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
+ }
+ Self::MerchantAccountNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
+ }
+ Self::MerchantConnectorAccountNotFound {id } => {
+ AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()})))
+ }
+ Self::MerchantConnectorAccountDisabled => {
+ AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
+ }
+ Self::ResourceIdNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
+ }
+ Self::MandateNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
+ }
+ Self::PayoutNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))
+ }
+ Self::EventNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None))
+ }
+ Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
+ Self::RefundNotPossible { connector } => {
+ AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
+ }
+ Self::MandateValidationFailed { reason } => {
+ AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() })))
+ }
+ Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
+ Self::PaymentBlockedError {
+ message,
+ reason,
+ ..
+ } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))),
+ Self::SuccessfulPaymentNotFound => {
+ AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
+ }
+ Self::IncorrectConnectorNameGiven => {
+ AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
+ }
+ Self::AddressNotFound => {
+ AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
+ },
+ Self::GenericNotFoundError { message } => {
+ AER::NotFound(ApiError::new("HE", 5, message, None))
+ },
+ Self::ApiKeyNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
+ }
+ Self::NotSupported { message } => {
+ AER::BadRequest(ApiError::new("HE", 3, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
+ },
+ Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)),
+ Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
+ Self::FlowNotSupported { flow, connector } => {
+ AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
+ }
+ Self::DisputeNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None))
+ },
+ Self::AuthenticationNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None))
+ },
+ Self::BusinessProfileNotFound { id } => {
+ AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None))
+ }
+ Self::FileNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None))
+ }
+ Self::PollNotFound { .. } => {
+ AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None))
+ },
+ Self::FileNotAvailable => {
+ AER::NotFound(ApiError::new("HE", 2, "File not available", None))
+ }
+ Self::DisputeStatusValidationFailed { .. } => {
+ AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None))
+ }
+ Self::FileValidationFailed { reason } => {
+ AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None))
+ }
+ Self::MissingFile => {
+ AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None))
+ }
+ Self::MissingFilePurpose => {
+ AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None))
+ }
+ Self::MissingFileContentType => {
+ AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None))
+ }
+ Self::MissingDisputeId => {
+ AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None))
+ }
+ Self::WebhookAuthenticationFailed => {
+ AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
+ }
+ Self::WebhookResourceNotFound => {
+ AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
+ }
+ Self::WebhookBadRequest => {
+ AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
+ }
+ Self::WebhookProcessingFailure => {
+ AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
+ },
+ Self::WebhookInvalidMerchantSecret => {
+ AER::BadRequest(ApiError::new("WE", 2, "Merchant Secret set for webhook source verificartion is invalid", None))
+ }
+ Self::IncorrectPaymentMethodConfiguration => {
+ AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None))
+ }
+ Self::WebhookUnprocessableEntity => {
+ AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
+ },
+ Self::ResourceBusy => {
+ AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
+ }
+ Self::PaymentLinkNotFound => {
+ AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
+ }
+ Self::InvalidConnectorConfiguration {config} => {
+ AER::BadRequest(ApiError::new("IR", 24, format!("Merchant connector account is configured with invalid {config}"), None))
+ }
+ Self::CurrencyConversionFailed => {
+ AER::Unprocessable(ApiError::new("HE", 2, "Failed to convert currency to minor unit", None))
+ }
+ Self::PaymentMethodDeleteFailed => {
+ AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
+ }
+ 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))
+ }
+ }
+ }
+}
+
+impl actix_web::ResponseError for ApiErrorResponse {
+ fn status_code(&self) -> StatusCode {
+ ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code()
+ }
+
+ fn error_response(&self) -> actix_web::HttpResponse {
+ ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response()
+ }
+}
+
+impl From<ApiErrorResponse> for router_data::ErrorResponse {
+ fn from(error: ApiErrorResponse) -> Self {
+ Self {
+ code: error.error_code(),
+ message: error.error_message(),
+ reason: None,
+ status_code: match error {
+ ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
+ _ => 500,
+ },
+ attempt_status: None,
+ connector_transaction_id: None,
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index b470b538d78..ba6ccdf839a 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -1,10 +1,12 @@
pub mod errors;
pub mod mandates;
pub mod payment_address;
+pub mod payment_method_data;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod router_data;
+pub mod router_request_types;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
new file mode 100644
index 00000000000..9dc85c103e9
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -0,0 +1,837 @@
+use common_utils::pii::{self, Email};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+// We need to derive Serialize and Deserialize because some parts of payment method data are being
+// stored in the database as serde_json::Value
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
+pub enum PaymentMethodData {
+ Card(Card),
+ CardRedirect(CardRedirectData),
+ Wallet(WalletData),
+ PayLater(PayLaterData),
+ BankRedirect(BankRedirectData),
+ BankDebit(BankDebitData),
+ BankTransfer(Box<BankTransferData>),
+ Crypto(CryptoData),
+ MandatePayment,
+ Reward,
+ Upi(UpiData),
+ Voucher(VoucherData),
+ GiftCard(Box<GiftCardData>),
+ CardToken(CardToken),
+}
+
+impl PaymentMethodData {
+ pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
+ match self {
+ Self::Card(_) => Some(common_enums::PaymentMethod::Card),
+ Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
+ Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
+ Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
+ Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
+ Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
+ Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
+ Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
+ Self::Reward => Some(common_enums::PaymentMethod::Reward),
+ Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
+ Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
+ Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
+ Self::CardToken(_) | Self::MandatePayment => None,
+ }
+ }
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
+pub struct Card {
+ pub card_number: cards::CardNumber,
+ pub card_exp_month: Secret<String>,
+ pub card_exp_year: Secret<String>,
+ pub card_cvc: Secret<String>,
+ pub card_issuer: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_type: Option<String>,
+ pub card_issuing_country: Option<String>,
+ pub bank_code: Option<String>,
+ pub nick_name: Option<Secret<String>>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
+pub enum CardRedirectData {
+ Knet {},
+ Benefit {},
+ MomoAtm {},
+ CardRedirect {},
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub enum PayLaterData {
+ KlarnaRedirect {},
+ KlarnaSdk { token: String },
+ AffirmRedirect {},
+ AfterpayClearpayRedirect {},
+ PayBrightRedirect {},
+ WalleyRedirect {},
+ AlmaRedirect {},
+ AtomeRedirect {},
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub enum WalletData {
+ AliPayQr(Box<AliPayQr>),
+ AliPayRedirect(AliPayRedirection),
+ AliPayHkRedirect(AliPayHkRedirection),
+ MomoRedirect(MomoRedirection),
+ KakaoPayRedirect(KakaoPayRedirection),
+ GoPayRedirect(GoPayRedirection),
+ GcashRedirect(GcashRedirection),
+ ApplePay(ApplePayWalletData),
+ ApplePayRedirect(Box<ApplePayRedirectData>),
+ ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
+ DanaRedirect {},
+ GooglePay(GooglePayWalletData),
+ GooglePayRedirect(Box<GooglePayRedirectData>),
+ GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
+ MbWayRedirect(Box<MbWayRedirection>),
+ MobilePayRedirect(Box<MobilePayRedirection>),
+ PaypalRedirect(PaypalRedirection),
+ PaypalSdk(PayPalWalletData),
+ SamsungPay(Box<SamsungPayWalletData>),
+ TwintRedirect {},
+ VippsRedirect {},
+ TouchNGoRedirect(Box<TouchNGoRedirection>),
+ WeChatPayRedirect(Box<WeChatPayRedirection>),
+ WeChatPayQr(Box<WeChatPayQr>),
+ CashappQr(Box<CashappQr>),
+ SwishQr(SwishQrData),
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub struct SamsungPayWalletData {
+ /// The encrypted payment token from Samsung
+ pub token: Secret<String>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub struct GooglePayWalletData {
+ /// The type of payment method
+ pub pm_type: String,
+ /// User-facing message to describe the payment method that funds this transaction.
+ pub description: String,
+ /// The information of the payment method
+ pub info: GooglePayPaymentMethodInfo,
+ /// The tokenization data of Google pay
+ pub tokenization_data: GpayTokenizationData,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplePayRedirectData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GooglePayRedirectData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GooglePayThirdPartySdkData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplePayThirdPartySdkData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct WeChatPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct WeChatPay {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct WeChatPayQr {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct CashappQr {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct PaypalRedirection {
+ /// paypal's email address
+ pub email: Option<Email>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AliPayQr {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AliPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct AliPayHkRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct MomoRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct KakaoPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GoPayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GcashRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct MobilePayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct MbWayRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+
+pub struct GooglePayPaymentMethodInfo {
+ /// The name of the card network
+ pub card_network: String,
+ /// The details of the card
+ pub card_details: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct PayPalWalletData {
+ /// Token generated for the Apple pay
+ pub token: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct TouchNGoRedirection {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct SwishQrData {}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct GpayTokenizationData {
+ /// The type of the token
+ pub token_type: String,
+ /// Token generated for the wallet
+ pub token: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplePayWalletData {
+ /// The payment data of Apple pay
+ pub payment_data: String,
+ /// The payment method of Apple pay
+ pub payment_method: ApplepayPaymentMethod,
+ /// The unique identifier for the transaction
+ pub transaction_identifier: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ApplepayPaymentMethod {
+ pub display_name: String,
+ pub network: String,
+ pub pm_type: String,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+
+pub enum BankRedirectData {
+ BancontactCard {
+ card_number: Option<cards::CardNumber>,
+ card_exp_month: Option<Secret<String>>,
+ card_exp_year: Option<Secret<String>>,
+ },
+ Bizum {},
+ Blik {
+ blik_code: Option<String>,
+ },
+ Eps {
+ bank_name: Option<common_enums::BankNames>,
+ },
+ Giropay {
+ bank_account_bic: Option<Secret<String>>,
+ bank_account_iban: Option<Secret<String>>,
+ },
+ Ideal {
+ bank_name: Option<common_enums::BankNames>,
+ },
+ Interac {},
+ OnlineBankingCzechRepublic {
+ issuer: common_enums::BankNames,
+ },
+ OnlineBankingFinland {},
+ OnlineBankingPoland {
+ issuer: common_enums::BankNames,
+ },
+ OnlineBankingSlovakia {
+ issuer: common_enums::BankNames,
+ },
+ OpenBankingUk {
+ issuer: Option<common_enums::BankNames>,
+ },
+ Przelewy24 {
+ bank_name: Option<common_enums::BankNames>,
+ },
+ Sofort {
+ preferred_language: Option<String>,
+ },
+ Trustly {},
+ OnlineBankingFpx {
+ issuer: common_enums::BankNames,
+ },
+ OnlineBankingThailand {
+ issuer: common_enums::BankNames,
+ },
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct CryptoData {
+ pub pay_currency: Option<String>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct UpiData {
+ pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum VoucherData {
+ Boleto(Box<BoletoVoucherData>),
+ Efecty,
+ PagoEfectivo,
+ RedCompra,
+ RedPagos,
+ Alfamart(Box<AlfamartVoucherData>),
+ Indomaret(Box<IndomaretVoucherData>),
+ Oxxo,
+ SevenEleven(Box<JCSVoucherData>),
+ Lawson(Box<JCSVoucherData>),
+ MiniStop(Box<JCSVoucherData>),
+ FamilyMart(Box<JCSVoucherData>),
+ Seicomart(Box<JCSVoucherData>),
+ PayEasy(Box<JCSVoucherData>),
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct BoletoVoucherData {
+ /// The shopper's social security number
+ pub social_security_number: Option<Secret<String>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct AlfamartVoucherData {}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct IndomaretVoucherData {}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct JCSVoucherData {}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum GiftCardData {
+ Givex(GiftCardDetails),
+ PaySafeCard {},
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct GiftCardDetails {
+ /// The gift card number
+ pub number: Secret<String>,
+ /// The card verification code.
+ pub cvc: Secret<String>,
+}
+
+#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
+#[serde(rename_all = "snake_case")]
+pub struct CardToken {
+ /// The card holder's name
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The CVC number for the card
+ pub card_cvc: Option<Secret<String>>,
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum BankDebitData {
+ AchBankDebit {
+ account_number: Secret<String>,
+ routing_number: Secret<String>,
+ bank_name: Option<common_enums::BankNames>,
+ bank_type: Option<common_enums::BankType>,
+ bank_holder_type: Option<common_enums::BankHolderType>,
+ },
+ SepaBankDebit {
+ iban: Secret<String>,
+ },
+ BecsBankDebit {
+ account_number: Secret<String>,
+ bsb_number: Secret<String>,
+ },
+ BacsBankDebit {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ },
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BankTransferData {
+ AchBankTransfer {},
+ SepaBankTransfer {},
+ BacsBankTransfer {},
+ MultibancoBankTransfer {},
+ PermataBankTransfer {},
+ BcaBankTransfer {},
+ BniVaBankTransfer {},
+ BriVaBankTransfer {},
+ CimbVaBankTransfer {},
+ DanamonVaBankTransfer {},
+ MandiriVaBankTransfer {},
+ Pix {},
+ Pse {},
+ LocalBankTransfer { bank_code: Option<String> },
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+pub struct SepaAndBacsBillingDetails {
+ /// The Email ID for SEPA and BACS billing
+ pub email: Email,
+ /// The billing name for SEPA and BACS billing
+ pub name: Secret<String>,
+}
+
+impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
+ fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
+ match api_model_payment_method_data {
+ api_models::payments::PaymentMethodData::Card(card_data) => {
+ Self::Card(Card::from(card_data))
+ }
+ api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {
+ Self::CardRedirect(From::from(card_redirect))
+ }
+ api_models::payments::PaymentMethodData::Wallet(wallet_data) => {
+ Self::Wallet(From::from(wallet_data))
+ }
+ api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {
+ Self::PayLater(From::from(pay_later_data))
+ }
+ api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
+ Self::BankRedirect(From::from(bank_redirect_data))
+ }
+ api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
+ Self::BankDebit(From::from(bank_debit_data))
+ }
+ api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
+ Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))
+ }
+ api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
+ Self::Crypto(From::from(crypto_data))
+ }
+ api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
+ api_models::payments::PaymentMethodData::Reward => Self::Reward,
+ api_models::payments::PaymentMethodData::Upi(upi_data) => {
+ Self::Upi(From::from(upi_data))
+ }
+ api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
+ Self::Voucher(From::from(voucher_data))
+ }
+ api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
+ Self::GiftCard(Box::new(From::from(*gift_card)))
+ }
+ api_models::payments::PaymentMethodData::CardToken(card_token) => {
+ Self::CardToken(From::from(card_token))
+ }
+ }
+ }
+}
+
+impl From<api_models::payments::Card> for Card {
+ fn from(value: api_models::payments::Card) -> Self {
+ let api_models::payments::Card {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name: _,
+ card_cvc,
+ card_issuer,
+ card_network,
+ card_type,
+ card_issuing_country,
+ bank_code,
+ nick_name,
+ } = value;
+
+ Self {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_cvc,
+ card_issuer,
+ card_network,
+ card_type,
+ card_issuing_country,
+ bank_code,
+ nick_name,
+ }
+ }
+}
+
+impl From<api_models::payments::CardRedirectData> for CardRedirectData {
+ fn from(value: api_models::payments::CardRedirectData) -> Self {
+ match value {
+ api_models::payments::CardRedirectData::Knet {} => Self::Knet {},
+ api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},
+ api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},
+ api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},
+ }
+ }
+}
+
+impl From<api_models::payments::WalletData> for WalletData {
+ fn from(value: api_models::payments::WalletData) -> Self {
+ match value {
+ api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),
+ api_models::payments::WalletData::AliPayRedirect(_) => {
+ Self::AliPayRedirect(AliPayRedirection {})
+ }
+ api_models::payments::WalletData::AliPayHkRedirect(_) => {
+ Self::AliPayHkRedirect(AliPayHkRedirection {})
+ }
+ api_models::payments::WalletData::MomoRedirect(_) => {
+ Self::MomoRedirect(MomoRedirection {})
+ }
+ api_models::payments::WalletData::KakaoPayRedirect(_) => {
+ Self::KakaoPayRedirect(KakaoPayRedirection {})
+ }
+ api_models::payments::WalletData::GoPayRedirect(_) => {
+ Self::GoPayRedirect(GoPayRedirection {})
+ }
+ api_models::payments::WalletData::GcashRedirect(_) => {
+ Self::GcashRedirect(GcashRedirection {})
+ }
+ api_models::payments::WalletData::ApplePay(apple_pay_data) => {
+ Self::ApplePay(ApplePayWalletData::from(apple_pay_data))
+ }
+ api_models::payments::WalletData::ApplePayRedirect(_) => {
+ Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))
+ }
+ api_models::payments::WalletData::ApplePayThirdPartySdk(_) => {
+ Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {}))
+ }
+ api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},
+ api_models::payments::WalletData::GooglePay(google_pay_data) => {
+ Self::GooglePay(GooglePayWalletData::from(google_pay_data))
+ }
+ api_models::payments::WalletData::GooglePayRedirect(_) => {
+ Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))
+ }
+ api_models::payments::WalletData::GooglePayThirdPartySdk(_) => {
+ Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {}))
+ }
+ api_models::payments::WalletData::MbWayRedirect(..) => {
+ Self::MbWayRedirect(Box::new(MbWayRedirection {}))
+ }
+ api_models::payments::WalletData::MobilePayRedirect(_) => {
+ Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))
+ }
+ api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {
+ Self::PaypalRedirect(PaypalRedirection {
+ email: paypal_redirect_data.email,
+ })
+ }
+ api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {
+ Self::PaypalSdk(PayPalWalletData {
+ token: paypal_sdk_data.token,
+ })
+ }
+ api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
+ Self::SamsungPay(Box::new(SamsungPayWalletData {
+ token: samsung_pay_data.token,
+ }))
+ }
+ api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
+ api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
+ api_models::payments::WalletData::TouchNGoRedirect(_) => {
+ Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))
+ }
+ api_models::payments::WalletData::WeChatPayRedirect(_) => {
+ Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))
+ }
+ api_models::payments::WalletData::WeChatPayQr(_) => {
+ Self::WeChatPayQr(Box::new(WeChatPayQr {}))
+ }
+ api_models::payments::WalletData::CashappQr(_) => {
+ Self::CashappQr(Box::new(CashappQr {}))
+ }
+ api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),
+ }
+ }
+}
+
+impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData {
+ fn from(value: api_models::payments::GooglePayWalletData) -> Self {
+ Self {
+ pm_type: value.pm_type,
+ description: value.description,
+ info: GooglePayPaymentMethodInfo {
+ card_network: value.info.card_network,
+ card_details: value.info.card_details,
+ },
+ tokenization_data: GpayTokenizationData {
+ token_type: value.tokenization_data.token_type,
+ token: value.tokenization_data.token,
+ },
+ }
+ }
+}
+
+impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
+ fn from(value: api_models::payments::ApplePayWalletData) -> Self {
+ Self {
+ payment_data: value.payment_data,
+ payment_method: ApplepayPaymentMethod {
+ display_name: value.payment_method.display_name,
+ network: value.payment_method.network,
+ pm_type: value.payment_method.pm_type,
+ },
+ transaction_identifier: value.transaction_identifier,
+ }
+ }
+}
+
+impl From<api_models::payments::PayLaterData> for PayLaterData {
+ fn from(value: api_models::payments::PayLaterData) -> Self {
+ match value {
+ api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
+ api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
+ api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
+ api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
+ Self::AfterpayClearpayRedirect {}
+ }
+ api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},
+ api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},
+ api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},
+ api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},
+ }
+ }
+}
+
+impl From<api_models::payments::BankRedirectData> for BankRedirectData {
+ fn from(value: api_models::payments::BankRedirectData) -> Self {
+ match value {
+ api_models::payments::BankRedirectData::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ ..
+ } => Self::BancontactCard {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ },
+ api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
+ api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
+ api_models::payments::BankRedirectData::Eps { bank_name, .. } => {
+ Self::Eps { bank_name }
+ }
+ api_models::payments::BankRedirectData::Giropay {
+ bank_account_bic,
+ bank_account_iban,
+ ..
+ } => Self::Giropay {
+ bank_account_bic,
+ bank_account_iban,
+ },
+ api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
+ Self::Ideal { bank_name }
+ }
+ api_models::payments::BankRedirectData::Interac { .. } => Self::Interac {},
+ api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
+ Self::OnlineBankingCzechRepublic { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingFinland { .. } => {
+ Self::OnlineBankingFinland {}
+ }
+ api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
+ Self::OnlineBankingPoland { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
+ Self::OnlineBankingSlovakia { issuer }
+ }
+ api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => {
+ Self::OpenBankingUk { issuer }
+ }
+ api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
+ Self::Przelewy24 { bank_name }
+ }
+ api_models::payments::BankRedirectData::Sofort {
+ preferred_language, ..
+ } => Self::Sofort { preferred_language },
+ api_models::payments::BankRedirectData::Trustly { .. } => Self::Trustly {},
+ api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
+ Self::OnlineBankingFpx { issuer }
+ }
+ api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
+ Self::OnlineBankingThailand { issuer }
+ }
+ }
+ }
+}
+
+impl From<api_models::payments::CryptoData> for CryptoData {
+ fn from(value: api_models::payments::CryptoData) -> Self {
+ let api_models::payments::CryptoData { pay_currency } = value;
+ Self { pay_currency }
+ }
+}
+
+impl From<api_models::payments::UpiData> for UpiData {
+ fn from(value: api_models::payments::UpiData) -> Self {
+ let api_models::payments::UpiData { vpa_id } = value;
+ Self { vpa_id }
+ }
+}
+
+impl From<api_models::payments::VoucherData> for VoucherData {
+ fn from(value: api_models::payments::VoucherData) -> Self {
+ match value {
+ api_models::payments::VoucherData::Boleto(boleto_data) => {
+ Self::Boleto(Box::new(BoletoVoucherData {
+ social_security_number: boleto_data.social_security_number,
+ }))
+ }
+ api_models::payments::VoucherData::Alfamart(_) => {
+ Self::Alfamart(Box::new(AlfamartVoucherData {}))
+ }
+ api_models::payments::VoucherData::Indomaret(_) => {
+ Self::Indomaret(Box::new(IndomaretVoucherData {}))
+ }
+ api_models::payments::VoucherData::SevenEleven(_)
+ | api_models::payments::VoucherData::Lawson(_)
+ | api_models::payments::VoucherData::MiniStop(_)
+ | api_models::payments::VoucherData::FamilyMart(_)
+ | api_models::payments::VoucherData::Seicomart(_)
+ | api_models::payments::VoucherData::PayEasy(_) => {
+ Self::SevenEleven(Box::new(JCSVoucherData {}))
+ }
+ api_models::payments::VoucherData::Efecty => Self::Efecty,
+ api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
+ api_models::payments::VoucherData::RedCompra => Self::RedCompra,
+ api_models::payments::VoucherData::RedPagos => Self::RedPagos,
+ api_models::payments::VoucherData::Oxxo => Self::Oxxo,
+ }
+ }
+}
+
+impl From<api_models::payments::GiftCardData> for GiftCardData {
+ fn from(value: api_models::payments::GiftCardData) -> Self {
+ match value {
+ api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
+ number: details.number,
+ cvc: details.cvc,
+ }),
+ api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
+ }
+ }
+}
+
+impl From<api_models::payments::CardToken> for CardToken {
+ fn from(value: api_models::payments::CardToken) -> Self {
+ let api_models::payments::CardToken {
+ card_holder_name,
+ card_cvc,
+ } = value;
+ Self {
+ card_holder_name,
+ card_cvc,
+ }
+ }
+}
+
+impl From<api_models::payments::BankDebitData> for BankDebitData {
+ fn from(value: api_models::payments::BankDebitData) -> Self {
+ match value {
+ api_models::payments::BankDebitData::AchBankDebit {
+ account_number,
+ routing_number,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ ..
+ } => Self::AchBankDebit {
+ account_number,
+ routing_number,
+ bank_name,
+ bank_type,
+ bank_holder_type,
+ },
+ api_models::payments::BankDebitData::SepaBankDebit { iban, .. } => {
+ Self::SepaBankDebit { iban }
+ }
+ api_models::payments::BankDebitData::BecsBankDebit {
+ account_number,
+ bsb_number,
+ ..
+ } => Self::BecsBankDebit {
+ account_number,
+ bsb_number,
+ },
+ api_models::payments::BankDebitData::BacsBankDebit {
+ account_number,
+ sort_code,
+ ..
+ } => Self::BacsBankDebit {
+ account_number,
+ sort_code,
+ },
+ }
+ }
+}
+
+impl From<api_models::payments::BankTransferData> for BankTransferData {
+ fn from(value: api_models::payments::BankTransferData) -> Self {
+ match value {
+ api_models::payments::BankTransferData::AchBankTransfer { .. } => {
+ Self::AchBankTransfer {}
+ }
+ api_models::payments::BankTransferData::SepaBankTransfer { .. } => {
+ Self::SepaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BacsBankTransfer { .. } => {
+ Self::BacsBankTransfer {}
+ }
+ api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
+ Self::MultibancoBankTransfer {}
+ }
+ api_models::payments::BankTransferData::PermataBankTransfer { .. } => {
+ Self::PermataBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BcaBankTransfer { .. } => {
+ Self::BcaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {
+ Self::BniVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {
+ Self::BriVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {
+ Self::CimbVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
+ Self::DanamonVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
+ Self::MandiriVaBankTransfer {}
+ }
+ api_models::payments::BankTransferData::Pix {} => Self::Pix {},
+ api_models::payments::BankTransferData::Pse {} => Self::Pse {},
+ api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {
+ Self::LocalBankTransfer { bank_code }
+ }
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
new file mode 100644
index 00000000000..e95f6efd373
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -0,0 +1,453 @@
+pub mod authentication;
+pub mod fraud_check;
+use api_models::payments::RequestSurchargeDetails;
+use common_utils::{consts, errors, pii};
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use masking::Secret;
+use serde::Serialize;
+use serde_with::serde_as;
+
+use super::payment_method_data::PaymentMethodData;
+use crate::{errors::api_error_response, mandates, payments, router_data};
+#[derive(Debug, Clone)]
+pub struct PaymentsAuthorizeData {
+ pub payment_method_data: PaymentMethodData,
+ /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
+ /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
+ /// ```
+ /// get_original_amount()
+ /// get_surcharge_amount()
+ /// get_tax_on_surcharge_amount()
+ /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
+ /// ```
+ pub amount: i64,
+ pub email: Option<pii::Email>,
+ pub customer_name: Option<Secret<String>>,
+ pub currency: storage_enums::Currency,
+ pub confirm: bool,
+ pub statement_descriptor_suffix: Option<String>,
+ pub statement_descriptor: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub router_return_url: Option<String>,
+ pub webhook_url: Option<String>,
+ pub complete_authorize_url: Option<String>,
+ // Mandates
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub mandate_id: Option<api_models::payments::MandateIds>,
+ pub off_session: Option<bool>,
+ pub customer_acceptance: Option<mandates::CustomerAcceptance>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub browser_info: Option<BrowserInformation>,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub order_category: Option<String>,
+ pub session_token: Option<String>,
+ pub enrolled_for_3ds: bool,
+ pub related_transaction_id: Option<String>,
+ pub payment_experience: Option<storage_enums::PaymentExperience>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub surcharge_details: Option<SurchargeDetails>,
+ pub customer_id: Option<String>,
+ pub request_incremental_authorization: bool,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub authentication_data: Option<AuthenticationData>,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct PaymentsCaptureData {
+ pub amount_to_capture: i64,
+ pub currency: storage_enums::Currency,
+ pub connector_transaction_id: String,
+ pub payment_amount: i64,
+ pub multiple_capture_data: Option<MultipleCaptureRequestData>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub browser_info: Option<BrowserInformation>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ // This metadata is used to store the metadata shared during the payment intent request.
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct PaymentsIncrementalAuthorizationData {
+ pub total_amount: i64,
+ pub additional_amount: i64,
+ pub currency: storage_enums::Currency,
+ pub reason: Option<String>,
+ pub connector_transaction_id: String,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct MultipleCaptureRequestData {
+ pub capture_sequence: i16,
+ pub capture_reference: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct AuthorizeSessionTokenData {
+ pub amount_to_capture: Option<i64>,
+ pub currency: storage_enums::Currency,
+ pub connector_transaction_id: String,
+ pub amount: Option<i64>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ConnectorCustomerData {
+ pub description: Option<String>,
+ pub email: Option<pii::Email>,
+ pub phone: Option<Secret<String>>,
+ pub name: Option<Secret<String>>,
+ pub preprocessing_id: Option<String>,
+ pub payment_method_data: PaymentMethodData,
+}
+
+#[derive(Debug, Clone)]
+pub struct PaymentMethodTokenizationData {
+ pub payment_method_data: PaymentMethodData,
+ pub browser_info: Option<BrowserInformation>,
+ pub currency: storage_enums::Currency,
+ pub amount: Option<i64>,
+}
+
+#[derive(Debug, Clone)]
+pub struct PaymentsPreProcessingData {
+ pub payment_method_data: Option<PaymentMethodData>,
+ pub amount: Option<i64>,
+ pub email: Option<pii::Email>,
+ pub currency: Option<storage_enums::Currency>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub router_return_url: Option<String>,
+ pub webhook_url: Option<String>,
+ pub complete_authorize_url: Option<String>,
+ pub surcharge_details: Option<SurchargeDetails>,
+ pub browser_info: Option<BrowserInformation>,
+ pub connector_transaction_id: Option<String>,
+ pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
+}
+
+#[derive(Debug, Clone)]
+pub struct CompleteAuthorizeData {
+ pub payment_method_data: Option<PaymentMethodData>,
+ pub amount: i64,
+ pub email: Option<pii::Email>,
+ pub currency: storage_enums::Currency,
+ pub confirm: bool,
+ pub statement_descriptor_suffix: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ // Mandates
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub mandate_id: Option<api_models::payments::MandateIds>,
+ pub off_session: Option<bool>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
+ pub browser_info: Option<BrowserInformation>,
+ pub connector_transaction_id: Option<String>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub complete_authorize_url: Option<String>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+}
+
+#[derive(Debug, Clone)]
+pub struct CompleteAuthorizeRedirectResponse {
+ pub params: Option<Secret<String>>,
+ pub payload: Option<pii::SecretSerdeValue>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsSyncData {
+ //TODO : add fields based on the connector requirements
+ pub connector_transaction_id: ResponseId,
+ pub encoded_data: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub connector_meta: Option<serde_json::Value>,
+ 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)]
+pub enum SyncRequestType {
+ MultipleCaptureSync(Vec<String>),
+ #[default]
+ SinglePaymentSync,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsCancelData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
+ pub connector_transaction_id: String,
+ pub cancellation_reason: Option<String>,
+ pub connector_meta: Option<serde_json::Value>,
+ pub browser_info: Option<BrowserInformation>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ // This metadata is used to store the metadata shared during the payment intent request.
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsRejectData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct PaymentsApproveData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
+}
+
+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
+pub struct BrowserInformation {
+ pub color_depth: Option<u8>,
+ pub java_enabled: Option<bool>,
+ pub java_script_enabled: Option<bool>,
+ pub language: Option<String>,
+ pub screen_height: Option<u32>,
+ pub screen_width: Option<u32>,
+ pub time_zone: Option<i32>,
+ pub ip_address: Option<std::net::IpAddr>,
+ pub accept_header: Option<String>,
+ pub user_agent: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+pub enum ResponseId {
+ ConnectorTransactionId(String),
+ EncodedData(String),
+ #[default]
+ NoResponseId,
+}
+impl ResponseId {
+ pub fn get_connector_transaction_id(
+ &self,
+ ) -> errors::CustomResult<String, errors::ValidationError> {
+ match self {
+ Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
+ _ => Err(errors::ValidationError::IncorrectValueProvided {
+ field_name: "connector_transaction_id",
+ })
+ .attach_printable("Expected connector transaction ID not found"),
+ }
+ }
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct SurchargeDetails {
+ /// original_amount
+ pub original_amount: common_utils::types::MinorUnit,
+ /// surcharge value
+ pub surcharge: common_utils::types::Surcharge,
+ /// tax on surcharge value
+ pub tax_on_surcharge:
+ Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
+ /// surcharge amount for this payment
+ pub surcharge_amount: common_utils::types::MinorUnit,
+ /// tax on surcharge amount for this payment
+ pub tax_on_surcharge_amount: common_utils::types::MinorUnit,
+ /// sum of original amount,
+ pub final_amount: common_utils::types::MinorUnit,
+}
+
+impl SurchargeDetails {
+ pub fn is_request_surcharge_matching(
+ &self,
+ request_surcharge_details: RequestSurchargeDetails,
+ ) -> bool {
+ request_surcharge_details.surcharge_amount == self.surcharge_amount
+ && request_surcharge_details.tax_amount.unwrap_or_default()
+ == self.tax_on_surcharge_amount
+ }
+ pub fn get_total_surcharge_amount(&self) -> common_utils::types::MinorUnit {
+ self.surcharge_amount + self.tax_on_surcharge_amount
+ }
+}
+
+impl
+ From<(
+ &RequestSurchargeDetails,
+ &payments::payment_attempt::PaymentAttempt,
+ )> for SurchargeDetails
+{
+ fn from(
+ (request_surcharge_details, payment_attempt): (
+ &RequestSurchargeDetails,
+ &payments::payment_attempt::PaymentAttempt,
+ ),
+ ) -> Self {
+ let surcharge_amount = request_surcharge_details.surcharge_amount;
+ let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default();
+ Self {
+ original_amount: payment_attempt.amount,
+ surcharge: common_utils::types::Surcharge::Fixed(
+ request_surcharge_details.surcharge_amount,
+ ),
+ tax_on_surcharge: None,
+ surcharge_amount,
+ tax_on_surcharge_amount,
+ final_amount: payment_attempt.amount + surcharge_amount + tax_on_surcharge_amount,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct AuthenticationData {
+ pub eci: Option<String>,
+ pub cavv: String,
+ pub threeds_server_transaction_id: String,
+ pub message_version: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct RefundsData {
+ pub refund_id: String,
+ pub connector_transaction_id: String,
+
+ pub connector_refund_id: Option<String>,
+ pub currency: storage_enums::Currency,
+ /// Amount for the payment against which this refund is issued
+ pub payment_amount: i64,
+ pub reason: Option<String>,
+ pub webhook_url: Option<String>,
+ /// Amount to be refunded
+ pub refund_amount: i64,
+ /// Arbitrary metadata required for refund
+ pub connector_metadata: Option<serde_json::Value>,
+ pub browser_info: Option<BrowserInformation>,
+}
+
+#[derive(Debug, Clone)]
+pub struct AccessTokenRequestData {
+ pub app_id: Secret<String>,
+ pub id: Option<Secret<String>>,
+ // Add more keys if required
+}
+
+impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData {
+ type Error = api_error_response::ApiErrorResponse;
+ fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match connector_auth {
+ router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ app_id: api_key,
+ id: None,
+ }),
+ router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+ router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+ router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+
+ _ => Err(api_error_response::ApiErrorResponse::InvalidDataValue {
+ field_name: "connector_account_details",
+ }),
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct AcceptDisputeRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct DefendDisputeRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct SubmitEvidenceRequestData {
+ pub dispute_id: String,
+ pub connector_dispute_id: String,
+ pub access_activity_log: Option<String>,
+ pub billing_address: Option<String>,
+ pub cancellation_policy: Option<Vec<u8>>,
+ pub cancellation_policy_provider_file_id: Option<String>,
+ pub cancellation_policy_disclosure: Option<String>,
+ pub cancellation_rebuttal: Option<String>,
+ pub customer_communication: Option<Vec<u8>>,
+ pub customer_communication_provider_file_id: Option<String>,
+ pub customer_email_address: Option<String>,
+ pub customer_name: Option<String>,
+ pub customer_purchase_ip: Option<String>,
+ pub customer_signature: Option<Vec<u8>>,
+ pub customer_signature_provider_file_id: Option<String>,
+ pub product_description: Option<String>,
+ pub receipt: Option<Vec<u8>>,
+ pub receipt_provider_file_id: Option<String>,
+ pub refund_policy: Option<Vec<u8>>,
+ pub refund_policy_provider_file_id: Option<String>,
+ pub refund_policy_disclosure: Option<String>,
+ pub refund_refusal_explanation: Option<String>,
+ pub service_date: Option<String>,
+ pub service_documentation: Option<Vec<u8>>,
+ pub service_documentation_provider_file_id: Option<String>,
+ pub shipping_address: Option<String>,
+ pub shipping_carrier: Option<String>,
+ pub shipping_date: Option<String>,
+ pub shipping_documentation: Option<Vec<u8>>,
+ pub shipping_documentation_provider_file_id: Option<String>,
+ pub shipping_tracking_number: Option<String>,
+ pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
+ pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
+ pub recurring_transaction_agreement: Option<Vec<u8>>,
+ pub recurring_transaction_agreement_provider_file_id: Option<String>,
+ pub uncategorized_file: Option<Vec<u8>>,
+ pub uncategorized_file_provider_file_id: Option<String>,
+ pub uncategorized_text: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+pub struct RetrieveFileRequestData {
+ pub provider_file_id: String,
+}
+
+#[serde_as]
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct UploadFileRequestData {
+ pub file_key: String,
+ #[serde(skip)]
+ pub file: Vec<u8>,
+ #[serde_as(as = "serde_with::DisplayFromStr")]
+ pub file_type: mime::Mime,
+ pub file_size: i32,
+}
+
+#[cfg(feature = "payouts")]
+#[derive(Debug, Clone)]
+pub struct PayoutsData {
+ pub payout_id: String,
+ pub amount: i64,
+ pub connector_payout_id: Option<String>,
+ pub destination_currency: storage_enums::Currency,
+ pub source_currency: storage_enums::Currency,
+ pub payout_type: storage_enums::PayoutType,
+ pub entity_type: storage_enums::PayoutEntityType,
+ pub customer_details: Option<CustomerDetails>,
+ pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>,
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct CustomerDetails {
+ pub customer_id: Option<String>,
+ pub name: Option<Secret<String, masking::WithType>>,
+ pub email: Option<pii::Email>,
+ pub phone: Option<Secret<String, masking::WithType>>,
+ pub phone_country_code: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct VerifyWebhookSourceRequestData {
+ pub webhook_headers: actix_web::http::header::HeaderMap,
+ pub webhook_body: Vec<u8>,
+ pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets,
+}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
new file mode 100644
index 00000000000..1a554e8054d
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
@@ -0,0 +1,182 @@
+use cards::CardNumber;
+use common_utils::{ext_traits::OptionExt, pii::Email};
+use error_stack::{Report, ResultExt};
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData,
+ router_request_types::BrowserInformation,
+};
+
+#[derive(Debug, Clone)]
+pub enum AuthenticationResponseData {
+ PreAuthNResponse {
+ threeds_server_transaction_id: String,
+ maximum_supported_3ds_version: common_utils::types::SemanticVersion,
+ connector_authentication_id: String,
+ three_ds_method_data: Option<String>,
+ three_ds_method_url: Option<String>,
+ message_version: common_utils::types::SemanticVersion,
+ connector_metadata: Option<serde_json::Value>,
+ },
+ AuthNResponse {
+ authn_flow_type: AuthNFlowType,
+ authentication_value: Option<String>,
+ trans_status: common_enums::TransactionStatus,
+ },
+ PostAuthNResponse {
+ trans_status: common_enums::TransactionStatus,
+ authentication_value: Option<String>,
+ eci: Option<String>,
+ },
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ChallengeParams {
+ pub acs_url: Option<url::Url>,
+ 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>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub enum AuthNFlowType {
+ Challenge(Box<ChallengeParams>),
+ Frictionless,
+}
+
+impl AuthNFlowType {
+ pub fn get_acs_url(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_url.as_ref().map(ToString::to_string)
+ } else {
+ None
+ }
+ }
+ pub fn get_challenge_request(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.challenge_request.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_acs_reference_number(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_reference_number.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_acs_trans_id(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_trans_id.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_acs_signed_content(&self) -> Option<String> {
+ if let Self::Challenge(challenge_params) = self {
+ challenge_params.acs_signed_content.clone()
+ } else {
+ None
+ }
+ }
+ pub fn get_decoupled_authentication_type(&self) -> common_enums::DecoupledAuthenticationType {
+ match self {
+ Self::Challenge(_) => common_enums::DecoupledAuthenticationType::Challenge,
+ Self::Frictionless => common_enums::DecoupledAuthenticationType::Frictionless,
+ }
+ }
+}
+
+#[derive(Clone, Default, Debug)]
+pub struct PreAuthNRequestData {
+ // card number
+ #[allow(dead_code)]
+ pub(crate) card_holder_account_number: CardNumber,
+}
+
+#[derive(Clone, Debug)]
+pub struct ConnectorAuthenticationRequestData {
+ pub payment_method_data: PaymentMethodData,
+ pub billing_address: api_models::payments::Address,
+ pub shipping_address: Option<api_models::payments::Address>,
+ pub browser_details: Option<BrowserInformation>,
+ pub amount: Option<i64>,
+ pub currency: Option<common_enums::Currency>,
+ pub message_category: MessageCategory,
+ pub device_channel: api_models::payments::DeviceChannel,
+ pub pre_authentication_data: PreAuthenticationData,
+ pub return_url: Option<String>,
+ pub sdk_information: Option<api_models::payments::SdkInformation>,
+ pub email: Option<Email>,
+ pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
+ pub three_ds_requestor_url: String,
+ pub webhook_url: String,
+}
+
+#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
+pub enum MessageCategory {
+ Payment,
+ NonPayment,
+}
+
+#[derive(Clone, Debug)]
+pub struct ConnectorPostAuthenticationRequestData {
+ pub threeds_server_transaction_id: String,
+}
+
+#[derive(Clone, Debug)]
+pub struct PreAuthenticationData {
+ pub threeds_server_transaction_id: String,
+ pub message_version: common_utils::types::SemanticVersion,
+ pub acquirer_bin: Option<String>,
+ pub acquirer_merchant_id: Option<String>,
+ pub connector_metadata: Option<serde_json::Value>,
+}
+
+impl TryFrom<&diesel_models::authentication::Authentication> for PreAuthenticationData {
+ type Error = Report<ApiErrorResponse>;
+
+ fn try_from(
+ authentication: &diesel_models::authentication::Authentication,
+ ) -> Result<Self, Self::Error> {
+ let error_message = ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() };
+ let threeds_server_transaction_id = authentication
+ .threeds_server_transaction_id
+ .clone()
+ .get_required_value("threeds_server_transaction_id")
+ .change_context(error_message.clone())?;
+ let message_version = authentication
+ .message_version
+ .clone()
+ .get_required_value("message_version")
+ .change_context(error_message)?;
+ Ok(Self {
+ threeds_server_transaction_id,
+ message_version,
+ acquirer_bin: authentication.acquirer_bin.clone(),
+ acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),
+ connector_metadata: authentication.connector_metadata.clone(),
+ })
+ }
+}
+
+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
+pub struct ThreeDsMethodData {
+ pub three_ds_method_data_submission: bool,
+ pub three_ds_method_data: String,
+ pub three_ds_method_url: Option<String>,
+}
+#[derive(Clone, Default, Debug, Serialize, Deserialize)]
+pub struct AcquirerDetails {
+ pub acquirer_bin: String,
+ pub acquirer_merchant_id: String,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+pub struct ExternalThreeDSConnectorMetadata {
+ pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
+}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
new file mode 100644
index 00000000000..441d3a70b41
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
@@ -0,0 +1,164 @@
+use api_models;
+use common_enums;
+use common_utils::{
+ events::{ApiEventMetric, ApiEventsType},
+ pii::Email,
+};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+use crate::router_request_types;
+#[derive(Debug, Clone)]
+pub struct FraudCheckSaleData {
+ pub amount: i64,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub currency: Option<common_enums::Currency>,
+ pub email: Option<Email>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckCheckoutData {
+ pub amount: i64,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub currency: Option<common_enums::Currency>,
+ pub browser_info: Option<router_request_types::BrowserInformation>,
+ pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
+ pub email: Option<Email>,
+ pub gateway: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckTransactionData {
+ pub amount: i64,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub currency: Option<common_enums::Currency>,
+ pub payment_method: Option<common_enums::PaymentMethod>,
+ pub error_code: Option<String>,
+ pub error_message: Option<String>,
+ pub connector_transaction_id: Option<String>,
+ //The name of the payment gateway or financial institution that processed the transaction.
+ pub connector: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckRecordReturnData {
+ pub amount: i64,
+ pub currency: Option<common_enums::Currency>,
+ pub refund_method: RefundMethod,
+ pub refund_transaction_id: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum RefundMethod {
+ StoreCredit,
+ OriginalPaymentInstrument,
+ NewPaymentInstrument,
+}
+
+#[derive(Debug, Clone)]
+pub struct FraudCheckFulfillmentData {
+ pub amount: i64,
+ pub order_details: Option<Vec<Secret<serde_json::Value>>>,
+ pub fulfillment_req: FrmFulfillmentRequest,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct FrmFulfillmentRequest {
+ ///unique payment_id for the transaction
+ #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
+ pub payment_id: String,
+ ///unique order_id for the order_details in the transaction
+ #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
+ pub order_id: String,
+ ///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
+ #[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
+ pub fulfillment_status: Option<FulfillmentStatus>,
+ ///contains details of the fulfillment
+ #[schema(value_type = Vec<Fulfillments>)]
+ pub fulfillments: Vec<Fulfillments>,
+ //name of the tracking Company
+ #[schema(max_length = 255, example = "fedex")]
+ pub tracking_company: Option<String>,
+ //tracking ID of the product
+ #[schema(example = r#"["track_8327446667", "track_8327446668"]"#)]
+ pub tracking_numbers: Option<Vec<String>>,
+ //tracking_url for tracking the product
+ pub tracking_urls: Option<Vec<String>>,
+ // The name of the Shipper.
+ pub carrier: Option<String>,
+ // Fulfillment method for the shipment.
+ pub fulfillment_method: Option<String>,
+ // Statuses to indicate shipment state.
+ pub shipment_status: Option<String>,
+ // The date and time items are ready to be shipped.
+ pub shipped_at: Option<String>,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Fulfillments {
+ ///shipment_id of the shipped items
+ #[schema(max_length = 255, example = "ship_101")]
+ pub shipment_id: String,
+ ///products sent in the shipment
+ #[schema(value_type = Option<Vec<Product>>)]
+ pub products: Option<Vec<Product>>,
+ ///destination address of the shipment
+ #[schema(value_type = Destination)]
+ pub destination: Destination,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde(untagged)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub enum FulfillmentStatus {
+ PARTIAL,
+ COMPLETE,
+ REPLACEMENT,
+ CANCELED,
+}
+
+#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Product {
+ pub item_name: String,
+ pub item_quantity: i64,
+ pub item_id: String,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Destination {
+ pub full_name: Secret<String>,
+ pub organization: Option<String>,
+ pub email: Option<Email>,
+ pub address: Address,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
+#[serde_with::skip_serializing_none]
+#[serde(rename_all = "snake_case")]
+pub struct Address {
+ pub street_address: Secret<String>,
+ pub unit: Option<Secret<String>>,
+ pub postal_code: Secret<String>,
+ pub city: String,
+ pub province_code: Secret<String>,
+ pub country_code: common_enums::CountryAlpha2,
+}
+
+impl ApiEventMetric for FrmFulfillmentRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::FraudCheck)
+ }
+}
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index bca1cbb64b8..528381061cf 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -1,7 +1,7 @@
-#![allow(unused_variables)]
use common_utils::errors::ErrorSwitch;
+use hyperswitch_domain_models::errors::api_error_response as errors;
-use crate::core::errors::{self, CustomersErrorResponse};
+use crate::core::errors::CustomersErrorResponse;
#[derive(Debug, router_derive::ApiError, Clone)]
#[error(error_type_enum = StripeErrorType)]
@@ -481,11 +481,11 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
Self::PaymentIntentPaymentAttemptFailed { data }
}
errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data },
- errors::ApiErrorResponse::InvalidCardData { data } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
- errors::ApiErrorResponse::CardExpired { data } => Self::ExpiredCard,
- errors::ApiErrorResponse::RefundNotPossible { connector } => Self::RefundFailed,
- errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map
- errors::ApiErrorResponse::PayoutFailed { data } => Self::PayoutFailed,
+ errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
+ errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard,
+ errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed,
+ errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map
+ errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed,
errors::ApiErrorResponse::MandateUpdateFailed
| errors::ApiErrorResponse::MandateSerializationFailed
@@ -605,7 +605,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
object: "poll".to_owned(),
id,
},
- errors::ApiErrorResponse::DisputeStatusValidationFailed { reason } => {
+ errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => {
Self::InternalServerError
}
errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed,
diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs
index 8c487f904f8..9ffae8a02de 100644
--- a/crates/router/src/connector/signifyd/transformers/api.rs
+++ b/crates/router/src/connector/signifyd/transformers/api.rs
@@ -1,6 +1,7 @@
use bigdecimal::ToPrimitive;
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::{self, ResultExt};
+pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -14,7 +15,7 @@ use crate::{
core::{errors, fraud_check::types as core_types},
types::{
self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums,
- ResponseId, ResponseRouterData,
+ transformers::ForeignFrom, ResponseId, ResponseRouterData,
},
};
@@ -509,7 +510,7 @@ impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFulfillmentSignifydReq
.fulfillment_status
.as_ref()
.map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())),
- fulfillments: Vec::<Fulfillments>::from(&item.request.fulfillment_req),
+ fulfillments: Vec::<Fulfillments>::foreign_from(&item.request.fulfillment_req),
})
}
}
@@ -525,8 +526,8 @@ impl From<&core_types::FulfillmentStatus> for FulfillmentStatus {
}
}
-impl From<&core_types::FrmFulfillmentRequest> for Vec<Fulfillments> {
- fn from(fulfillment_req: &core_types::FrmFulfillmentRequest) -> Self {
+impl ForeignFrom<&core_types::FrmFulfillmentRequest> for Vec<Fulfillments> {
+ fn foreign_from(fulfillment_req: &core_types::FrmFulfillmentRequest) -> Self {
fulfillment_req
.fulfillments
.iter()
@@ -643,15 +644,6 @@ pub struct SignifydPaymentsRecordReturnRequest {
refund: SignifydRefund,
}
-#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum RefundMethod {
- StoreCredit,
- OriginalPaymentInstrument,
- NewPaymentInstrument,
-}
-
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 495d176ab9e..af1a0787d9d 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -24,6 +24,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignTryFrom,
ErrorResponse, Response,
},
utils::BytesExt,
@@ -225,7 +226,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
Ok(types::PaymentsCancelRouterData {
status: enums::AttemptStatus::Voided,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::try_from(response.links)?,
+ resource_id: types::ResponseId::foreign_try_from(response.links)?,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -392,7 +393,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
Ok(types::PaymentsCaptureRouterData {
status: enums::AttemptStatus::Charged,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::try_from(response.links)?,
+ resource_id: types::ResponseId::foreign_try_from(response.links)?,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs
index 0a50885d28e..14ccbc1fac8 100644
--- a/crates/router/src/connector/worldpay/response.rs
+++ b/crates/router/src/connector/worldpay/response.rs
@@ -1,7 +1,7 @@
use masking::Secret;
use serde::{Deserialize, Serialize};
-use crate::{core::errors, types};
+use crate::{core::errors, types, types::transformers::ForeignTryFrom};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPaymentsResponse {
@@ -109,9 +109,9 @@ impl TryFrom<Option<PaymentLinks>> for ResponseIdStr {
}
}
-impl TryFrom<Option<PaymentLinks>> for types::ResponseId {
+impl ForeignTryFrom<Option<PaymentLinks>> for types::ResponseId {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(links: Option<PaymentLinks>) -> Result<Self, Self::Error> {
+ fn foreign_try_from(links: Option<PaymentLinks>) -> Result<Self, Self::Error> {
get_resource_id(links, Self::ConnectorTransactionId)
}
}
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 9c908cf749d..5f0fd9f332f 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -9,7 +9,9 @@ use crate::{
connector::utils,
consts,
core::errors,
- types::{self, domain, PaymentsAuthorizeData, PaymentsResponseData},
+ types::{
+ self, domain, transformers::ForeignTryFrom, PaymentsAuthorizeData, PaymentsResponseData,
+ },
};
#[derive(Debug, Serialize)]
@@ -245,7 +247,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>>
},
description: item.response.description,
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::try_from(item.response.links)?,
+ resource_id: types::ResponseId::foreign_try_from(item.response.links)?,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index a70a97e7bf0..3a8cab8c516 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -1,4 +1,3 @@
-pub mod api_error_response;
pub mod customers_error_response;
pub mod error_handlers;
pub mod transformers;
@@ -11,7 +10,10 @@ use std::fmt::Display;
use actix_web::{body::BoxBody, ResponseError};
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
use diesel_models::errors as storage_errors;
-pub use hyperswitch_domain_models::errors::StorageError as DataStorageError;
+pub use hyperswitch_domain_models::errors::{
+ api_error_response::{ApiErrorResponse, ErrorType, NotImplementedMessage},
+ StorageError as DataStorageError,
+};
pub use redis_interface::errors::RedisError;
use scheduler::errors as sch_errors;
use storage_impl::errors as storage_impl_errors;
@@ -19,7 +21,6 @@ use storage_impl::errors as storage_impl_errors;
pub use user::*;
pub use self::{
- api_error_response::{ApiErrorResponse, NotImplementedMessage},
customers_error_response::CustomersErrorResponse,
sch_errors::*,
storage_errors::*,
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
deleted file mode 100644
index 0c492f0f089..00000000000
--- a/crates/router/src/core/errors/api_error_response.rs
+++ /dev/null
@@ -1,328 +0,0 @@
-#![allow(dead_code, unused_variables)]
-
-use http::StatusCode;
-use scheduler::errors::{PTError, ProcessTrackerError};
-
-#[derive(Clone, Debug, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ErrorType {
- InvalidRequestError,
- ObjectNotFound,
- RouterError,
- ProcessingError,
- BadGateway,
- ServerNotAvailable,
- DuplicateRequest,
- ValidationError,
- ConnectorError,
- LockTimeout,
-}
-
-#[allow(dead_code)]
-#[derive(Debug, Clone, router_derive::ApiError)]
-#[error(error_type_enum = ErrorType)]
-pub enum ApiErrorResponse {
- #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")]
- NotImplemented { message: NotImplementedMessage },
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_01",
- message = "API key not provided or invalid API key used"
- )]
- Unauthorized,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")]
- InvalidRequestUrl,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")]
- InvalidHttpMethod,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")]
- MissingRequiredField { field_name: &'static str },
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_05",
- message = "{field_name} contains invalid data. Expected format is {expected_format}"
- )]
- InvalidDataFormat {
- field_name: String,
- expected_format: String,
- },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")]
- InvalidRequestData { message: String },
- /// Typically used when a field has invalid value, or deserialization of the value contained in a field fails.
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")]
- InvalidDataValue { field_name: &'static str },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")]
- ClientSecretNotGiven,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")]
- ClientSecretExpired,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")]
- ClientSecretInvalid,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")]
- MandateActive,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")]
- CustomerRedacted,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")]
- MaximumRefundCount,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")]
- RefundAmountExceedsPaymentAmount,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")]
- PaymentUnexpectedState {
- current_flow: String,
- field_name: String,
- current_value: String,
- states: String,
- },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]
- InvalidEphemeralKey,
- /// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]
- PreconditionFailed { message: String },
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_17",
- message = "Access forbidden, invalid JWT token was used"
- )]
- InvalidJwtToken,
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_18",
- message = "{message}",
- )]
- GenericUnauthorized { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
- NotSupported { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")]
- FlowNotSupported { flow: String, connector: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
- MissingRequiredFields { field_names: Vec<&'static str> },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
- AccessForbidden { resource: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
- FileProviderNotSupported { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
- UnprocessableEntity { message: String },
- #[error(
- error_type = ErrorType::ProcessingError, code = "IR_24",
- message = "Invalid {wallet_name} wallet token"
- )]
- InvalidWalletToken { wallet_name: String },
- #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
- ExternalConnectorError {
- code: String,
- message: String,
- connector: String,
- status_code: u16,
- reason: Option<String>,
- },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")]
- PaymentAuthorizationFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")]
- PaymentAuthenticationFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")]
- PaymentCaptureFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]
- InvalidCardData { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::InvalidRequestError, code = "CE_04", message = "Payout validation failed")]
- PayoutFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]
- CardExpired { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]
- RefundFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")]
- VerificationFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")]
- DisputeFailed { data: Option<serde_json::Value> },
- #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]
- InternalServerError,
- #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]
- ResourceBusy,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]
- DuplicateRefundRequest,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]
- DuplicateMandate,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
- DuplicateMerchantAccount,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
- DuplicateMerchantConnectorAccount {
- profile_id: String,
- connector_label: String,
- },
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
- DuplicatePaymentMethod,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")]
- DuplicatePayment { payment_id: String },
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id}' already exists in our records")]
- DuplicatePayout { payout_id: String },
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")]
- DuplicateConfig,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")]
- RefundNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]
- CustomerNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "RE_02", message = "Config key does not exist in our records.")]
- ConfigNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")]
- PaymentNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")]
- PaymentMethodNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")]
- MerchantAccountNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")]
- MerchantConnectorAccountNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")]
- BusinessProfileNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")]
- PollNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")]
- ResourceIdNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")]
- MandateNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")]
- AuthenticationNotFound { id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")]
- MandateUpdateFailed,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]
- ApiKeyNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]
- PayoutNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")]
- EventNotFound,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]
- MandateSerializationFailed,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]
- MandateDeserializationFailed,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")]
- ReturnUrlUnavailable,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")]
- RefundNotPossible { connector: String },
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )]
- MandateValidationFailed { reason: String },
- #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")]
- PaymentNotSucceeded,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")]
- MerchantConnectorAccountDisabled,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")]
- PaymentBlockedError {
- code: u16,
- message: String,
- status: String,
- reason: String,
- },
- #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")]
- SuccessfulPaymentNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")]
- IncorrectConnectorNameGiven,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")]
- AddressNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")]
- DisputeNotFound { dispute_id: String },
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")]
- FileNotFound,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")]
- FileNotAvailable,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute status validation failed")]
- DisputeStatusValidationFailed { reason: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Card with the provided iin does not exist")]
- InvalidCardIin,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")]
- InvalidCardIinLength,
- #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")]
- FileValidationFailed { reason: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File not found / valid in the request")]
- MissingFile,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "Dispute id not found in the request")]
- MissingDisputeId,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File purpose not found in the request or is invalid")]
- MissingFilePurpose,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File content type not found / valid")]
- MissingFileContentType,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_05", message = "{message}")]
- GenericNotFoundError { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_01", message = "{message}")]
- GenericDuplicateError { message: String },
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
- WebhookAuthenticationFailed,
- #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")]
- WebhookResourceNotFound,
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
- WebhookBadRequest,
- #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")]
- WebhookProcessingFailure,
- #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "required payment method is not configured or configured incorrectly for all configured connectors")]
- IncorrectPaymentMethodConfiguration,
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")]
- WebhookUnprocessableEntity,
- #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")]
- PaymentLinkNotFound,
- #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Merchant Secret set my merchant for webhook source verification is invalid")]
- WebhookInvalidMerchantSecret,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
- CurrencyNotSupported { message: String },
- #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")]
- HealthCheckError {
- component: &'static str,
- message: String,
- },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_24", message = "Merchant connector account is configured with invalid {config}")]
- InvalidConnectorConfiguration { config: String },
- #[error(error_type = ErrorType::ValidationError, code = "HE_01", message = "Failed to convert currency to minor unit")]
- CurrencyConversionFailed,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
- PaymentMethodDeleteFailed,
- #[error(
- error_type = ErrorType::InvalidRequestError, code = "IR_26",
- message = "Invalid Cookie"
- )]
- InvalidCookie,
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
- ExtendedCardInfoNotFound,
-}
-
-impl PTError for ApiErrorResponse {
- fn to_pt_error(&self) -> ProcessTrackerError {
- ProcessTrackerError::EApiErrorResponse
- }
-}
-
-#[derive(Clone)]
-pub enum NotImplementedMessage {
- Reason(String),
- Default,
-}
-
-impl std::fmt::Debug for NotImplementedMessage {
- fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::Reason(message) => write!(fmt, "{message} is not implemented"),
- Self::Default => {
- write!(
- fmt,
- "This API is under development and will be made available soon."
- )
- }
- }
- }
-}
-
-impl ::core::fmt::Display for ApiErrorResponse {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- r#"{{"error":{}}}"#,
- serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
- )
- }
-}
-
-impl actix_web::ResponseError for ApiErrorResponse {
- fn status_code(&self) -> StatusCode {
- common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
- self,
- )
- .status_code()
- }
-
- fn error_response(&self) -> actix_web::HttpResponse {
- common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
- self,
- )
- .error_response()
- }
-}
-
-impl crate::services::EmbedError for error_stack::Report<ApiErrorResponse> {}
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index 880c0d7b20b..df529f81803 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -1,312 +1,7 @@
-use api_models::errors::types::Extra;
use common_utils::errors::ErrorSwitch;
-use http::StatusCode;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
-use super::{ApiErrorResponse, ConnectorError, CustomersErrorResponse, StorageError};
-
-impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
- fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
- use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
-
- match self {
- Self::NotImplemented { message } => {
- AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
- }
- Self::Unauthorized => AER::Unauthorized(ApiError::new(
- "IR",
- 1,
- "API key not provided or invalid API key used", None
- )),
- Self::InvalidRequestUrl => {
- AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
- }
- Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
- "IR",
- 3,
- "The HTTP method is not applicable for this API", None
- )),
- Self::MissingRequiredField { field_name } => AER::BadRequest(
- ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
- ),
- Self::InvalidDataFormat {
- field_name,
- expected_format,
- } => AER::Unprocessable(ApiError::new(
- "IR",
- 5,
- format!(
- "{field_name} contains invalid data. Expected format is {expected_format}"
- ), None
- )),
- Self::InvalidRequestData { message } => {
- AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
- }
- Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
- "IR",
- 7,
- format!("Invalid value provided: {field_name}"), None
- )),
- Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
- "IR",
- 8,
- "client_secret was not provided", None
- )),
- Self::ClientSecretInvalid => {
- AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
- }
- Self::CurrencyNotSupported { message } => {
- AER::BadRequest(ApiError::new("IR", 9, message, None))
- }
- Self::MandateActive => {
- AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
- }
- Self::CustomerRedacted => {
- AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
- }
- Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
- Self::RefundAmountExceedsPaymentAmount => {
- AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
- }
- Self::PaymentUnexpectedState {
- current_flow,
- field_name,
- current_value,
- states,
- } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
- Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
- Self::PreconditionFailed { message } => {
- AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
- }
- Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
- Self::GenericUnauthorized { message } => {
- AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
- },
- Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
- "IR",
- 19,
- "The provided client_secret has expired", None
- )),
- Self::MissingRequiredFields { field_names } => AER::BadRequest(
- ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
- ),
- Self::AccessForbidden {resource} => {
- AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
- },
- Self::FileProviderNotSupported { message } => {
- AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
- },
- Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 23, message.to_string(), None)),
- Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
- "IR",
- 24,
- format!("Invalid {wallet_name} wallet token"), None
- )),
- Self::ExternalConnectorError {
- code,
- message,
- connector,
- reason,
- status_code,
- } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned().map(Into::into), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
- Self::PaymentAuthorizationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::PaymentAuthenticationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::PaymentCaptureFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::DisputeFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 1, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
- }
- Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
- Self::VerificationFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
- },
- Self::MandateUpdateFailed | Self::MandateSerializationFailed | Self::MandateDeserializationFailed | Self::InternalServerError => {
- AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
- },
- Self::HealthCheckError { message,component } => {
- AER::InternalServerError(ApiError::new("HE",0,format!("{} health check failed with error: {}",component,message),None))
- },
- Self::PayoutFailed { data } => {
- AER::BadRequest(ApiError::new("CE", 4, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
- },
- Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
- Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
- Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
- Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => {
- AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None))
- }
- Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
- Self::DuplicatePayment { payment_id } => {
- AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id} already exists")), ..Default::default()})))
- }
- Self::DuplicatePayout { payout_id } => {
- AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id}' already exists in our records"), None))
- }
- Self::GenericDuplicateError { message } => {
- AER::BadRequest(ApiError::new("HE", 1, message, None))
- }
- Self::RefundNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
- }
- Self::CustomerNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
- }
- Self::ConfigNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
- },
- Self::DuplicateConfig => {
- AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
- }
- Self::PaymentNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
- }
- Self::PaymentMethodNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
- }
- Self::MerchantAccountNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
- }
- Self::MerchantConnectorAccountNotFound {id } => {
- AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()})))
- }
- Self::MerchantConnectorAccountDisabled => {
- AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
- }
- Self::ResourceIdNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
- }
- Self::MandateNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
- }
- Self::PayoutNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))
- }
- Self::EventNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None))
- }
- Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
- Self::RefundNotPossible { connector } => {
- AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
- }
- Self::MandateValidationFailed { reason } => {
- AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() })))
- }
- Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
- Self::PaymentBlockedError {
- message,
- reason,
- ..
- } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))),
- Self::SuccessfulPaymentNotFound => {
- AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
- }
- Self::IncorrectConnectorNameGiven => {
- AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
- }
- Self::AddressNotFound => {
- AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
- },
- Self::GenericNotFoundError { message } => {
- AER::NotFound(ApiError::new("HE", 5, message, None))
- },
- Self::ApiKeyNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
- }
- Self::NotSupported { message } => {
- AER::BadRequest(ApiError::new("HE", 3, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
- },
- Self::InvalidCardIin => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN does not exist", None)),
- Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("HE", 3, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
- Self::FlowNotSupported { flow, connector } => {
- AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
- }
- Self::DisputeNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Dispute does not exist in our records", None))
- },
- Self::AuthenticationNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None))
- },
- Self::BusinessProfileNotFound { id } => {
- AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None))
- }
- Self::FileNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "File does not exist in our records", None))
- }
- Self::PollNotFound { .. } => {
- AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None))
- },
- Self::FileNotAvailable => {
- AER::NotFound(ApiError::new("HE", 2, "File not available", None))
- }
- Self::DisputeStatusValidationFailed { .. } => {
- AER::BadRequest(ApiError::new("HE", 2, "Dispute status validation failed", None))
- }
- Self::FileValidationFailed { reason } => {
- AER::BadRequest(ApiError::new("HE", 2, format!("File validation failed {reason}"), None))
- }
- Self::MissingFile => {
- AER::BadRequest(ApiError::new("HE", 2, "File not found in the request", None))
- }
- Self::MissingFilePurpose => {
- AER::BadRequest(ApiError::new("HE", 2, "File purpose not found in the request or is invalid", None))
- }
- Self::MissingFileContentType => {
- AER::BadRequest(ApiError::new("HE", 2, "File content type not found", None))
- }
- Self::MissingDisputeId => {
- AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None))
- }
- Self::WebhookAuthenticationFailed => {
- AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
- }
- Self::WebhookResourceNotFound => {
- AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
- }
- Self::WebhookBadRequest => {
- AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
- }
- Self::WebhookProcessingFailure => {
- AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
- },
- Self::WebhookInvalidMerchantSecret => {
- AER::BadRequest(ApiError::new("WE", 2, "Merchant Secret set for webhook source verificartion is invalid", None))
- }
- Self::IncorrectPaymentMethodConfiguration => {
- AER::BadRequest(ApiError::new("HE", 4, "No eligible connector was found for the current payment method configuration", None))
- }
- Self::WebhookUnprocessableEntity => {
- AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
- },
- Self::ResourceBusy => {
- AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
- }
- Self::PaymentLinkNotFound => {
- AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
- }
- Self::InvalidConnectorConfiguration {config} => {
- AER::BadRequest(ApiError::new("IR", 24, format!("Merchant connector account is configured with invalid {config}"), None))
- }
- Self::CurrencyConversionFailed => {
- AER::Unprocessable(ApiError::new("HE", 2, "Failed to convert currency to minor unit", None))
- }
- Self::PaymentMethodDeleteFailed => {
- AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
- }
- 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))
- }
- }
- }
-}
+use super::{ConnectorError, CustomersErrorResponse, StorageError};
impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
fn switch(&self) -> ApiErrorResponse {
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index 678a351a4c3..1e2f5a2c305 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -158,9 +158,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
- reason.to_string(),
- ),
+ message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
.into()
}
@@ -249,7 +247,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
reason.to_string(),
),
}
@@ -476,9 +474,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
- reason.to_string(),
- ),
+ message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs
index d2a9b920457..bc30ad83b14 100644
--- a/crates/router/src/core/fraud_check/types.rs
+++ b/crates/router/src/core/fraud_check/types.rs
@@ -5,20 +5,20 @@ use api_models::{
refunds::RefundResponse,
};
use common_enums::FrmSuggestion;
-use common_utils::pii::{Email, SecretSerdeValue};
+use common_utils::pii::SecretSerdeValue;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+pub use hyperswitch_domain_models::router_request_types::fraud_check::{
+ Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product,
+};
use masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
use super::operation::BoxedFraudCheckOperation;
-use crate::{
- pii::Secret,
- types::{
- domain::MerchantAccount,
- storage::{enums as storage_enums, fraud_check::FraudCheck},
- PaymentAddress,
- },
+use crate::types::{
+ domain::MerchantAccount,
+ storage::{enums as storage_enums, fraud_check::FraudCheck},
+ PaymentAddress,
};
#[derive(Clone, Default, Debug)]
@@ -106,98 +106,6 @@ pub struct FrmFulfillmentSignifydApiRequest {
pub fulfillments: Vec<Fulfillments>,
}
-#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
-#[serde(deny_unknown_fields)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct FrmFulfillmentRequest {
- ///unique payment_id for the transaction
- #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
- pub payment_id: String,
- ///unique order_id for the order_details in the transaction
- #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
- pub order_id: String,
- ///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
- #[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
- pub fulfillment_status: Option<FulfillmentStatus>,
- ///contains details of the fulfillment
- #[schema(value_type = Vec<Fulfillments>)]
- pub fulfillments: Vec<Fulfillments>,
- //name of the tracking Company
- #[schema(max_length = 255, example = "fedex")]
- pub tracking_company: Option<String>,
- //tracking ID of the product
- #[schema(example = r#"["track_8327446667", "track_8327446668"]"#)]
- pub tracking_numbers: Option<Vec<String>>,
- //tracking_url for tracking the product
- pub tracking_urls: Option<Vec<String>>,
- // The name of the Shipper.
- pub carrier: Option<String>,
- // Fulfillment method for the shipment.
- pub fulfillment_method: Option<String>,
- // Statuses to indicate shipment state.
- pub shipment_status: Option<String>,
- // The date and time items are ready to be shipped.
- pub shipped_at: Option<String>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Fulfillments {
- ///shipment_id of the shipped items
- #[schema(max_length = 255, example = "ship_101")]
- pub shipment_id: String,
- ///products sent in the shipment
- #[schema(value_type = Option<Vec<Product>>)]
- pub products: Option<Vec<Product>>,
- ///destination address of the shipment
- #[schema(value_type = Destination)]
- pub destination: Destination,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde(untagged)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub enum FulfillmentStatus {
- PARTIAL,
- COMPLETE,
- REPLACEMENT,
- CANCELED,
-}
-
-#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Product {
- pub item_name: String,
- pub item_quantity: i64,
- pub item_id: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Destination {
- pub full_name: Secret<String>,
- pub organization: Option<String>,
- pub email: Option<Email>,
- pub address: Address,
-}
-
-#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
-#[serde_with::skip_serializing_none]
-#[serde(rename_all = "snake_case")]
-pub struct Address {
- pub street_address: Secret<String>,
- pub unit: Option<Secret<String>>,
- pub postal_code: Secret<String>,
- pub city: String,
- pub province_code: Secret<String>,
- pub country_code: common_enums::CountryAlpha2,
-}
-
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct FrmFulfillmentResponse {
///unique order_id for the transaction
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 9b2082cf31f..a6befa5269e 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -34,10 +34,11 @@ use error_stack::{report, ResultExt};
use events::EventInfo;
use futures::future::join_all;
use helpers::ApplePayData;
-use hyperswitch_domain_models::{
+pub use hyperswitch_domain_models::{
mandates::{CustomerAcceptance, MandateData},
payment_address::PaymentAddress,
router_data::RouterData,
+ router_request_types::CustomerDetails,
};
use masking::{ExposeInterface, Secret};
use redis_interface::errors::RedisError;
@@ -2488,15 +2489,6 @@ pub struct IncrementalAuthorizationDetails {
pub authorization_id: Option<String>,
}
-#[derive(Debug, Default, Clone)]
-pub struct CustomerDetails {
- pub customer_id: Option<String>,
- pub name: Option<Secret<String, masking::WithType>>,
- pub email: Option<pii::Email>,
- pub phone: Option<Secret<String, masking::WithType>>,
- pub phone_country_code: Option<String>,
-}
-
pub trait CustomerDetailsExt {
type Error;
fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error>;
diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs
index 92f815f6b5f..95ca0c3e31c 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -3,7 +3,7 @@ use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult},
+ errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::AppState,
diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs
index 726993aa7fa..638efa054eb 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -3,7 +3,7 @@ use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult},
+ errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::AppState,
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index f74ec42075a..7c6c6336fcb 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -150,7 +150,7 @@ where
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 71b7d84b9f9..e3a1daf39ac 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -1,8 +1,7 @@
use std::{collections::HashMap, num::TryFromIntError};
-use api_models::{payment_methods::SurchargeDetailsResponse, payments::RequestSurchargeDetails};
+use api_models::payment_methods::SurchargeDetailsResponse;
use common_utils::{
- consts,
errors::CustomResult,
ext_traits::{Encode, OptionExt},
types as common_types,
@@ -10,6 +9,7 @@ use common_utils::{
use diesel_models::business_profile::BusinessProfile;
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
+pub use hyperswitch_domain_models::router_request_types::{AuthenticationData, SurchargeDetails};
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
@@ -186,40 +186,6 @@ impl MultipleCaptureData {
}
}
-#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct SurchargeDetails {
- /// original_amount
- pub original_amount: common_types::MinorUnit,
- /// surcharge value
- pub surcharge: common_types::Surcharge,
- /// tax on surcharge value
- pub tax_on_surcharge:
- Option<common_types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
- /// surcharge amount for this payment
- pub surcharge_amount: common_types::MinorUnit,
- /// tax on surcharge amount for this payment
- pub tax_on_surcharge_amount: common_types::MinorUnit,
- /// sum of original amount,
- pub final_amount: common_types::MinorUnit,
-}
-
-impl From<(&RequestSurchargeDetails, &PaymentAttempt)> for SurchargeDetails {
- fn from(
- (request_surcharge_details, payment_attempt): (&RequestSurchargeDetails, &PaymentAttempt),
- ) -> Self {
- let surcharge_amount = request_surcharge_details.surcharge_amount;
- let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default();
- Self {
- original_amount: payment_attempt.amount,
- surcharge: common_types::Surcharge::Fixed(request_surcharge_details.surcharge_amount), // need to check this
- tax_on_surcharge: None,
- surcharge_amount,
- tax_on_surcharge_amount,
- final_amount: payment_attempt.amount + surcharge_amount + tax_on_surcharge_amount,
- }
- }
-}
-
impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse {
type Error = TryFromIntError;
fn foreign_try_from(
@@ -250,20 +216,6 @@ impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsRe
}
}
-impl SurchargeDetails {
- pub fn is_request_surcharge_matching(
- &self,
- request_surcharge_details: RequestSurchargeDetails,
- ) -> bool {
- request_surcharge_details.surcharge_amount == self.surcharge_amount
- && request_surcharge_details.tax_amount.unwrap_or_default()
- == self.tax_on_surcharge_amount
- }
- pub fn get_total_surcharge_amount(&self) -> common_types::MinorUnit {
- self.surcharge_amount + self.tax_on_surcharge_amount
- }
-}
-
#[derive(Eq, Hash, PartialEq, Clone, Debug, strum::Display)]
pub enum SurchargeKey {
Token(String),
@@ -387,14 +339,6 @@ impl SurchargeMetadata {
}
}
-#[derive(Debug, Clone)]
-pub struct AuthenticationData {
- pub eci: Option<String>,
- pub cavv: String,
- pub threeds_server_transaction_id: String,
- pub message_version: String,
-}
-
impl ForeignTryFrom<&storage::Authentication> for AuthenticationData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(authentication: &storage::Authentication) -> Result<Self, Self::Error> {
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index a7dcfa864a0..7cb929db94a 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -81,7 +81,7 @@ pub async fn do_gsm_multiple_connector_actions(
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
@@ -145,7 +145,7 @@ pub async fn do_gsm_single_connector_actions(
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
- message: errors::api_error_response::NotImplementedMessage::Reason(
+ message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs
index fe3d752497a..802a4ec3c63 100644
--- a/crates/router/src/core/verification.rs
+++ b/crates/router/src/core/verification.rs
@@ -4,7 +4,7 @@ use common_utils::{errors::CustomResult, request::RequestContent};
use error_stack::ResultExt;
use masking::ExposeInterface;
-use crate::{core::errors::api_error_response, headers, logger, routes::AppState, services};
+use crate::{core::errors, headers, logger, routes::AppState, services};
const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant";
@@ -12,10 +12,8 @@ pub async fn verify_merchant_creds_for_applepay(
state: AppState,
body: verifications::ApplepayMerchantVerificationRequest,
merchant_id: String,
-) -> CustomResult<
- services::ApplicationResponse<ApplepayMerchantResponse>,
- api_error_response::ApiErrorResponse,
-> {
+) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse>
+{
let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();
let applepay_internal_merchant_identifier = applepay_merchant_configs
@@ -55,7 +53,7 @@ pub async fn verify_merchant_creds_for_applepay(
utils::log_applepay_verification_response_if_error(&response);
let applepay_response =
- response.change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
+ response.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Error is already logged
match applepay_response {
@@ -67,7 +65,7 @@ pub async fn verify_merchant_creds_for_applepay(
body.domain_names.clone(),
)
.await
- .change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::api::ApplicationResponse::Json(
ApplepayMerchantResponse {
status_message: "Applepay verification Completed".to_string(),
@@ -76,7 +74,7 @@ pub async fn verify_merchant_creds_for_applepay(
}
Err(error) => {
logger::error!(?error);
- Err(api_error_response::ApiErrorResponse::InvalidRequestData {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Applepay verification Failed".to_string(),
}
.into())
@@ -90,13 +88,13 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
merchant_connector_id: String,
) -> CustomResult<
services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,
- api_error_response::ApiErrorResponse,
+ errors::ApiErrorResponse,
> {
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())
.await
- .change_context(api_error_response::ApiErrorResponse::MerchantAccountNotFound)?;
+ .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let verified_domains = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
@@ -105,7 +103,7 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
&key_store,
)
.await
- .change_context(api_error_response::ApiErrorResponse::ResourceIdNotFound)?
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?
.applepay_verified_domains
.unwrap_or_default();
diff --git a/crates/router/src/routes/fraud_check.rs b/crates/router/src/routes/fraud_check.rs
index f0b73015f3c..70bd55b7105 100644
--- a/crates/router/src/routes/fraud_check.rs
+++ b/crates/router/src/routes/fraud_check.rs
@@ -34,9 +34,3 @@ impl ApiEventMetric for FraudCheckResponseData {
Some(ApiEventsType::FraudCheck)
}
}
-
-impl ApiEventMetric for frm_core::types::FrmFulfillmentRequest {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::FraudCheck)
- }
-}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 71c74099ded..287f98cdb79 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1328,6 +1328,11 @@ impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> {
}
}
+impl EmbedError
+ for Report<hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse>
+{
+}
+
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 0afef760517..7f2f0764b5f 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -22,10 +22,11 @@ pub use api_models::{enums::Connector, mandates};
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
use common_enums::MandateStatus;
-use common_utils::{pii, pii::Email};
-pub use common_utils::{request::RequestContent, types::MinorUnit};
-use error_stack::ResultExt;
+pub use common_utils::request::RequestContent;
+use common_utils::{pii, pii::Email, types::MinorUnit};
use hyperswitch_domain_models::mandates::{CustomerAcceptance, MandateData};
+#[cfg(feature = "payouts")]
+pub use hyperswitch_domain_models::router_request_types::PayoutsData;
pub use hyperswitch_domain_models::{
payment_address::PaymentAddress,
router_data::{
@@ -33,9 +34,13 @@ pub use hyperswitch_domain_models::{
ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse,
PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData,
},
+ router_request_types::{
+ AcceptDisputeRequestData, AccessTokenRequestData, BrowserInformation,
+ DefendDisputeRequestData, RefundsData, ResponseId, RetrieveFileRequestData,
+ SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData,
+ },
};
use masking::Secret;
-use serde::Serialize;
use self::storage::enums as storage_enums;
pub use crate::core::payments::CustomerDetails;
@@ -51,7 +56,10 @@ use crate::{
payments::{types, PaymentData},
},
services,
- types::{transformers::ForeignFrom, types::AuthenticationData},
+ types::{
+ transformers::{ForeignFrom, ForeignTryFrom},
+ types::AuthenticationData,
+ },
};
pub type PaymentsAuthorizeRouterData =
RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
@@ -275,20 +283,6 @@ pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
-#[cfg(feature = "payouts")]
-#[derive(Debug, Clone)]
-pub struct PayoutsData {
- pub payout_id: String,
- pub amount: i64,
- pub connector_payout_id: Option<String>,
- pub destination_currency: storage_enums::Currency,
- pub source_currency: storage_enums::Currency,
- pub payout_type: storage_enums::PayoutType,
- pub entity_type: storage_enums::PayoutEntityType,
- pub customer_details: Option<CustomerDetails>,
- pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>,
-}
-
#[cfg(feature = "payouts")]
pub trait PayoutIndividualDetailsExt {
type Error;
@@ -534,13 +528,6 @@ pub struct SetupMandateRequestData {
pub metadata: Option<pii::SecretSerdeValue>,
}
-#[derive(Debug, Clone)]
-pub struct AccessTokenRequestData {
- pub app_id: Secret<String>,
- pub id: Option<Secret<String>>,
- // Add more keys if required
-}
-
pub trait Capturable {
fn get_captured_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
where
@@ -868,60 +855,6 @@ pub enum PreprocessingResponseId {
ConnectorTransactionId(String),
}
-#[derive(Debug, Clone, Default, Serialize)]
-pub enum ResponseId {
- ConnectorTransactionId(String),
- EncodedData(String),
- #[default]
- NoResponseId,
-}
-
-impl ResponseId {
- pub fn get_connector_transaction_id(
- &self,
- ) -> errors::CustomResult<String, errors::ValidationError> {
- match self {
- Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
- _ => Err(errors::ValidationError::IncorrectValueProvided {
- field_name: "connector_transaction_id",
- })
- .attach_printable("Expected connector transaction ID not found"),
- }
- }
-}
-
-#[derive(Debug, Clone)]
-pub struct RefundsData {
- pub refund_id: String,
- pub connector_transaction_id: String,
-
- pub connector_refund_id: Option<String>,
- pub currency: storage_enums::Currency,
- /// Amount for the payment against which this refund is issued
- pub payment_amount: i64,
- pub reason: Option<String>,
- pub webhook_url: Option<String>,
- /// Amount to be refunded
- pub refund_amount: i64,
- /// Arbitrary metadata required for refund
- pub connector_metadata: Option<serde_json::Value>,
- pub browser_info: Option<BrowserInformation>,
-}
-
-#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
-pub struct BrowserInformation {
- pub color_depth: Option<u8>,
- pub java_enabled: Option<bool>,
- pub java_script_enabled: Option<bool>,
- pub language: Option<String>,
- pub screen_height: Option<u32>,
- pub screen_width: Option<u32>,
- pub time_zone: Option<i32>,
- pub ip_address: Option<std::net::IpAddr>,
- pub accept_header: Option<String>,
- pub user_agent: Option<String>,
-}
-
#[derive(Debug, Clone)]
pub struct RefundsResponseData {
pub connector_refund_id: String,
@@ -935,13 +868,6 @@ pub enum Redirection {
NoRedirect,
}
-#[derive(Debug, Clone)]
-pub struct VerifyWebhookSourceRequestData {
- pub webhook_headers: actix_web::http::header::HeaderMap,
- pub webhook_body: Vec<u8>,
- pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets,
-}
-
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceResponseData {
pub verify_webhook_status: VerifyWebhookStatus,
@@ -953,98 +879,28 @@ pub enum VerifyWebhookStatus {
SourceNotVerified,
}
-#[derive(Default, Debug, Clone)]
-pub struct AcceptDisputeRequestData {
- pub dispute_id: String,
- pub connector_dispute_id: String,
-}
-
#[derive(Default, Clone, Debug)]
pub struct AcceptDisputeResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
-#[derive(Default, Debug, Clone)]
-pub struct SubmitEvidenceRequestData {
- pub dispute_id: String,
- pub connector_dispute_id: String,
- pub access_activity_log: Option<String>,
- pub billing_address: Option<String>,
- pub cancellation_policy: Option<Vec<u8>>,
- pub cancellation_policy_provider_file_id: Option<String>,
- pub cancellation_policy_disclosure: Option<String>,
- pub cancellation_rebuttal: Option<String>,
- pub customer_communication: Option<Vec<u8>>,
- pub customer_communication_provider_file_id: Option<String>,
- pub customer_email_address: Option<String>,
- pub customer_name: Option<String>,
- pub customer_purchase_ip: Option<String>,
- pub customer_signature: Option<Vec<u8>>,
- pub customer_signature_provider_file_id: Option<String>,
- pub product_description: Option<String>,
- pub receipt: Option<Vec<u8>>,
- pub receipt_provider_file_id: Option<String>,
- pub refund_policy: Option<Vec<u8>>,
- pub refund_policy_provider_file_id: Option<String>,
- pub refund_policy_disclosure: Option<String>,
- pub refund_refusal_explanation: Option<String>,
- pub service_date: Option<String>,
- pub service_documentation: Option<Vec<u8>>,
- pub service_documentation_provider_file_id: Option<String>,
- pub shipping_address: Option<String>,
- pub shipping_carrier: Option<String>,
- pub shipping_date: Option<String>,
- pub shipping_documentation: Option<Vec<u8>>,
- pub shipping_documentation_provider_file_id: Option<String>,
- pub shipping_tracking_number: Option<String>,
- pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
- pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
- pub recurring_transaction_agreement: Option<Vec<u8>>,
- pub recurring_transaction_agreement_provider_file_id: Option<String>,
- pub uncategorized_file: Option<Vec<u8>>,
- pub uncategorized_file_provider_file_id: Option<String>,
- pub uncategorized_text: Option<String>,
-}
-
#[derive(Default, Clone, Debug)]
pub struct SubmitEvidenceResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
-#[derive(Default, Debug, Clone)]
-pub struct DefendDisputeRequestData {
- pub dispute_id: String,
- pub connector_dispute_id: String,
-}
-
#[derive(Default, Debug, Clone)]
pub struct DefendDisputeResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
-#[derive(Clone, Debug, serde::Serialize)]
-pub struct UploadFileRequestData {
- pub file_key: String,
- #[serde(skip)]
- pub file: Vec<u8>,
- #[serde(serialize_with = "crate::utils::custom_serde::display_serialize")]
- pub file_type: mime::Mime,
- pub file_size: i32,
-}
-
#[derive(Default, Clone, Debug)]
pub struct UploadFileResponse {
pub provider_file_id: String,
}
-
-#[derive(Clone, Debug)]
-pub struct RetrieveFileRequestData {
- pub provider_file_id: String,
-}
-
#[derive(Clone, Debug)]
pub struct RetrieveFileResponse {
pub file_data: Vec<u8>,
@@ -1210,9 +1066,9 @@ pub struct Response {
pub status_code: u16,
}
-impl TryFrom<ConnectorAuthType> for AccessTokenRequestData {
+impl ForeignTryFrom<ConnectorAuthType> for AccessTokenRequestData {
type Error = errors::ApiErrorResponse;
- fn try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn foreign_try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
match connector_auth {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
app_id: api_key,
@@ -1238,22 +1094,6 @@ impl TryFrom<ConnectorAuthType> for AccessTokenRequestData {
}
}
-impl From<errors::ApiErrorResponse> for ErrorResponse {
- fn from(error: errors::ApiErrorResponse) -> Self {
- Self {
- code: error.error_code(),
- message: error.error_message(),
- reason: None,
- status_code: match error {
- errors::ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
- _ => 500,
- },
- attempt_status: None,
- connector_transaction_id: None,
- }
- }
-}
-
impl From<&&mut PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData {
fn from(data: &&mut PaymentsAuthorizeRouterData) -> Self {
Self {
diff --git a/crates/router/src/types/api/authentication.rs b/crates/router/src/types/api/authentication.rs
index 0f86f462167..9837059dc01 100644
--- a/crates/router/src/types/api/authentication.rs
+++ b/crates/router/src/types/api/authentication.rs
@@ -3,6 +3,7 @@ use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
+pub use hyperswitch_domain_models::router_request_types::authentication::MessageCategory;
use super::BoxedConnector;
use crate::core::errors;
@@ -66,12 +67,6 @@ pub struct PostAuthenticationResponse {
pub eci: Option<String>,
}
-#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
-pub enum MessageCategory {
- Payment,
- NonPayment,
-}
-
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
pub struct ExternalAuthenticationPayload {
pub trans_status: common_enums::TransactionStatus,
diff --git a/crates/router/src/types/api/files.rs b/crates/router/src/types/api/files.rs
index 873516ee71b..688962bd836 100644
--- a/crates/router/src/types/api/files.rs
+++ b/crates/router/src/types/api/files.rs
@@ -1,5 +1,6 @@
use api_models::enums::FileUploadProvider;
use masking::{Deserialize, Serialize};
+use serde_with::serde_as;
use super::ConnectorCommon;
use crate::{
@@ -47,12 +48,13 @@ impl ForeignTryFrom<&types::Connector> for FileUploadProvider {
}
}
+#[serde_as]
#[derive(Debug, Clone, serde::Serialize)]
pub struct CreateFileRequest {
pub file: Vec<u8>,
pub file_name: Option<String>,
pub file_size: i32,
- #[serde(serialize_with = "crate::utils::custom_serde::display_serialize")]
+ #[serde_as(as = "serde_with::DisplayFromStr")]
pub file_type: mime::Mime,
pub purpose: FilePurpose,
pub dispute_id: Option<String>,
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 9dc85c103e9..7b1f3365490 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -1,837 +1,10 @@
-use common_utils::pii::{self, Email};
-use masking::Secret;
-use serde::{Deserialize, Serialize};
-
-// We need to derive Serialize and Deserialize because some parts of payment method data are being
-// stored in the database as serde_json::Value
-#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
-pub enum PaymentMethodData {
- Card(Card),
- CardRedirect(CardRedirectData),
- Wallet(WalletData),
- PayLater(PayLaterData),
- BankRedirect(BankRedirectData),
- BankDebit(BankDebitData),
- BankTransfer(Box<BankTransferData>),
- Crypto(CryptoData),
- MandatePayment,
- Reward,
- Upi(UpiData),
- Voucher(VoucherData),
- GiftCard(Box<GiftCardData>),
- CardToken(CardToken),
-}
-
-impl PaymentMethodData {
- pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
- match self {
- Self::Card(_) => Some(common_enums::PaymentMethod::Card),
- Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
- Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
- Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
- Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
- Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
- Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
- Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
- Self::Reward => Some(common_enums::PaymentMethod::Reward),
- Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
- Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
- Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
- Self::CardToken(_) | Self::MandatePayment => None,
- }
- }
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
-pub struct Card {
- pub card_number: cards::CardNumber,
- pub card_exp_month: Secret<String>,
- pub card_exp_year: Secret<String>,
- pub card_cvc: Secret<String>,
- pub card_issuer: Option<String>,
- pub card_network: Option<common_enums::CardNetwork>,
- pub card_type: Option<String>,
- pub card_issuing_country: Option<String>,
- pub bank_code: Option<String>,
- pub nick_name: Option<Secret<String>>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
-pub enum CardRedirectData {
- Knet {},
- Benefit {},
- MomoAtm {},
- CardRedirect {},
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub enum PayLaterData {
- KlarnaRedirect {},
- KlarnaSdk { token: String },
- AffirmRedirect {},
- AfterpayClearpayRedirect {},
- PayBrightRedirect {},
- WalleyRedirect {},
- AlmaRedirect {},
- AtomeRedirect {},
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub enum WalletData {
- AliPayQr(Box<AliPayQr>),
- AliPayRedirect(AliPayRedirection),
- AliPayHkRedirect(AliPayHkRedirection),
- MomoRedirect(MomoRedirection),
- KakaoPayRedirect(KakaoPayRedirection),
- GoPayRedirect(GoPayRedirection),
- GcashRedirect(GcashRedirection),
- ApplePay(ApplePayWalletData),
- ApplePayRedirect(Box<ApplePayRedirectData>),
- ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
- DanaRedirect {},
- GooglePay(GooglePayWalletData),
- GooglePayRedirect(Box<GooglePayRedirectData>),
- GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
- MbWayRedirect(Box<MbWayRedirection>),
- MobilePayRedirect(Box<MobilePayRedirection>),
- PaypalRedirect(PaypalRedirection),
- PaypalSdk(PayPalWalletData),
- SamsungPay(Box<SamsungPayWalletData>),
- TwintRedirect {},
- VippsRedirect {},
- TouchNGoRedirect(Box<TouchNGoRedirection>),
- WeChatPayRedirect(Box<WeChatPayRedirection>),
- WeChatPayQr(Box<WeChatPayQr>),
- CashappQr(Box<CashappQr>),
- SwishQr(SwishQrData),
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub struct SamsungPayWalletData {
- /// The encrypted payment token from Samsung
- pub token: Secret<String>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub struct GooglePayWalletData {
- /// The type of payment method
- pub pm_type: String,
- /// User-facing message to describe the payment method that funds this transaction.
- pub description: String,
- /// The information of the payment method
- pub info: GooglePayPaymentMethodInfo,
- /// The tokenization data of Google pay
- pub tokenization_data: GpayTokenizationData,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplePayRedirectData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GooglePayRedirectData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GooglePayThirdPartySdkData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplePayThirdPartySdkData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct WeChatPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct WeChatPay {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct WeChatPayQr {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct CashappQr {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct PaypalRedirection {
- /// paypal's email address
- pub email: Option<Email>,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct AliPayQr {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct AliPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct AliPayHkRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct MomoRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct KakaoPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GoPayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GcashRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct MobilePayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct MbWayRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
-pub struct GooglePayPaymentMethodInfo {
- /// The name of the card network
- pub card_network: String,
- /// The details of the card
- pub card_details: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct PayPalWalletData {
- /// Token generated for the Apple pay
- pub token: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct TouchNGoRedirection {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct SwishQrData {}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct GpayTokenizationData {
- /// The type of the token
- pub token_type: String,
- /// Token generated for the wallet
- pub token: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplePayWalletData {
- /// The payment data of Apple pay
- pub payment_data: String,
- /// The payment method of Apple pay
- pub payment_method: ApplepayPaymentMethod,
- /// The unique identifier for the transaction
- pub transaction_identifier: String,
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ApplepayPaymentMethod {
- pub display_name: String,
- pub network: String,
- pub pm_type: String,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-
-pub enum BankRedirectData {
- BancontactCard {
- card_number: Option<cards::CardNumber>,
- card_exp_month: Option<Secret<String>>,
- card_exp_year: Option<Secret<String>>,
- },
- Bizum {},
- Blik {
- blik_code: Option<String>,
- },
- Eps {
- bank_name: Option<common_enums::BankNames>,
- },
- Giropay {
- bank_account_bic: Option<Secret<String>>,
- bank_account_iban: Option<Secret<String>>,
- },
- Ideal {
- bank_name: Option<common_enums::BankNames>,
- },
- Interac {},
- OnlineBankingCzechRepublic {
- issuer: common_enums::BankNames,
- },
- OnlineBankingFinland {},
- OnlineBankingPoland {
- issuer: common_enums::BankNames,
- },
- OnlineBankingSlovakia {
- issuer: common_enums::BankNames,
- },
- OpenBankingUk {
- issuer: Option<common_enums::BankNames>,
- },
- Przelewy24 {
- bank_name: Option<common_enums::BankNames>,
- },
- Sofort {
- preferred_language: Option<String>,
- },
- Trustly {},
- OnlineBankingFpx {
- issuer: common_enums::BankNames,
- },
- OnlineBankingThailand {
- issuer: common_enums::BankNames,
- },
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub struct CryptoData {
- pub pay_currency: Option<String>,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub struct UpiData {
- pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum VoucherData {
- Boleto(Box<BoletoVoucherData>),
- Efecty,
- PagoEfectivo,
- RedCompra,
- RedPagos,
- Alfamart(Box<AlfamartVoucherData>),
- Indomaret(Box<IndomaretVoucherData>),
- Oxxo,
- SevenEleven(Box<JCSVoucherData>),
- Lawson(Box<JCSVoucherData>),
- MiniStop(Box<JCSVoucherData>),
- FamilyMart(Box<JCSVoucherData>),
- Seicomart(Box<JCSVoucherData>),
- PayEasy(Box<JCSVoucherData>),
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct BoletoVoucherData {
- /// The shopper's social security number
- pub social_security_number: Option<Secret<String>>,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct AlfamartVoucherData {}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct IndomaretVoucherData {}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
-pub struct JCSVoucherData {}
-
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub enum GiftCardData {
- Givex(GiftCardDetails),
- PaySafeCard {},
-}
-
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub struct GiftCardDetails {
- /// The gift card number
- pub number: Secret<String>,
- /// The card verification code.
- pub cvc: Secret<String>,
-}
-
-#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
-#[serde(rename_all = "snake_case")]
-pub struct CardToken {
- /// The card holder's name
- pub card_holder_name: Option<Secret<String>>,
-
- /// The CVC number for the card
- pub card_cvc: Option<Secret<String>>,
-}
-
-#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub enum BankDebitData {
- AchBankDebit {
- account_number: Secret<String>,
- routing_number: Secret<String>,
- bank_name: Option<common_enums::BankNames>,
- bank_type: Option<common_enums::BankType>,
- bank_holder_type: Option<common_enums::BankHolderType>,
- },
- SepaBankDebit {
- iban: Secret<String>,
- },
- BecsBankDebit {
- account_number: Secret<String>,
- bsb_number: Secret<String>,
- },
- BacsBankDebit {
- account_number: Secret<String>,
- sort_code: Secret<String>,
- },
-}
-
-#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum BankTransferData {
- AchBankTransfer {},
- SepaBankTransfer {},
- BacsBankTransfer {},
- MultibancoBankTransfer {},
- PermataBankTransfer {},
- BcaBankTransfer {},
- BniVaBankTransfer {},
- BriVaBankTransfer {},
- CimbVaBankTransfer {},
- DanamonVaBankTransfer {},
- MandiriVaBankTransfer {},
- Pix {},
- Pse {},
- LocalBankTransfer { bank_code: Option<String> },
-}
-
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
-pub struct SepaAndBacsBillingDetails {
- /// The Email ID for SEPA and BACS billing
- pub email: Email,
- /// The billing name for SEPA and BACS billing
- pub name: Secret<String>,
-}
-
-impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
- fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
- match api_model_payment_method_data {
- api_models::payments::PaymentMethodData::Card(card_data) => {
- Self::Card(Card::from(card_data))
- }
- api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {
- Self::CardRedirect(From::from(card_redirect))
- }
- api_models::payments::PaymentMethodData::Wallet(wallet_data) => {
- Self::Wallet(From::from(wallet_data))
- }
- api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {
- Self::PayLater(From::from(pay_later_data))
- }
- api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
- Self::BankRedirect(From::from(bank_redirect_data))
- }
- api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
- Self::BankDebit(From::from(bank_debit_data))
- }
- api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
- Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))
- }
- api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
- Self::Crypto(From::from(crypto_data))
- }
- api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
- api_models::payments::PaymentMethodData::Reward => Self::Reward,
- api_models::payments::PaymentMethodData::Upi(upi_data) => {
- Self::Upi(From::from(upi_data))
- }
- api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
- Self::Voucher(From::from(voucher_data))
- }
- api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
- Self::GiftCard(Box::new(From::from(*gift_card)))
- }
- api_models::payments::PaymentMethodData::CardToken(card_token) => {
- Self::CardToken(From::from(card_token))
- }
- }
- }
-}
-
-impl From<api_models::payments::Card> for Card {
- fn from(value: api_models::payments::Card) -> Self {
- let api_models::payments::Card {
- card_number,
- card_exp_month,
- card_exp_year,
- card_holder_name: _,
- card_cvc,
- card_issuer,
- card_network,
- card_type,
- card_issuing_country,
- bank_code,
- nick_name,
- } = value;
-
- Self {
- card_number,
- card_exp_month,
- card_exp_year,
- card_cvc,
- card_issuer,
- card_network,
- card_type,
- card_issuing_country,
- bank_code,
- nick_name,
- }
- }
-}
-
-impl From<api_models::payments::CardRedirectData> for CardRedirectData {
- fn from(value: api_models::payments::CardRedirectData) -> Self {
- match value {
- api_models::payments::CardRedirectData::Knet {} => Self::Knet {},
- api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},
- api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},
- api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},
- }
- }
-}
-
-impl From<api_models::payments::WalletData> for WalletData {
- fn from(value: api_models::payments::WalletData) -> Self {
- match value {
- api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),
- api_models::payments::WalletData::AliPayRedirect(_) => {
- Self::AliPayRedirect(AliPayRedirection {})
- }
- api_models::payments::WalletData::AliPayHkRedirect(_) => {
- Self::AliPayHkRedirect(AliPayHkRedirection {})
- }
- api_models::payments::WalletData::MomoRedirect(_) => {
- Self::MomoRedirect(MomoRedirection {})
- }
- api_models::payments::WalletData::KakaoPayRedirect(_) => {
- Self::KakaoPayRedirect(KakaoPayRedirection {})
- }
- api_models::payments::WalletData::GoPayRedirect(_) => {
- Self::GoPayRedirect(GoPayRedirection {})
- }
- api_models::payments::WalletData::GcashRedirect(_) => {
- Self::GcashRedirect(GcashRedirection {})
- }
- api_models::payments::WalletData::ApplePay(apple_pay_data) => {
- Self::ApplePay(ApplePayWalletData::from(apple_pay_data))
- }
- api_models::payments::WalletData::ApplePayRedirect(_) => {
- Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))
- }
- api_models::payments::WalletData::ApplePayThirdPartySdk(_) => {
- Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {}))
- }
- api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},
- api_models::payments::WalletData::GooglePay(google_pay_data) => {
- Self::GooglePay(GooglePayWalletData::from(google_pay_data))
- }
- api_models::payments::WalletData::GooglePayRedirect(_) => {
- Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))
- }
- api_models::payments::WalletData::GooglePayThirdPartySdk(_) => {
- Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {}))
- }
- api_models::payments::WalletData::MbWayRedirect(..) => {
- Self::MbWayRedirect(Box::new(MbWayRedirection {}))
- }
- api_models::payments::WalletData::MobilePayRedirect(_) => {
- Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))
- }
- api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {
- Self::PaypalRedirect(PaypalRedirection {
- email: paypal_redirect_data.email,
- })
- }
- api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {
- Self::PaypalSdk(PayPalWalletData {
- token: paypal_sdk_data.token,
- })
- }
- api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
- Self::SamsungPay(Box::new(SamsungPayWalletData {
- token: samsung_pay_data.token,
- }))
- }
- api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
- api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
- api_models::payments::WalletData::TouchNGoRedirect(_) => {
- Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))
- }
- api_models::payments::WalletData::WeChatPayRedirect(_) => {
- Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))
- }
- api_models::payments::WalletData::WeChatPayQr(_) => {
- Self::WeChatPayQr(Box::new(WeChatPayQr {}))
- }
- api_models::payments::WalletData::CashappQr(_) => {
- Self::CashappQr(Box::new(CashappQr {}))
- }
- api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),
- }
- }
-}
-
-impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData {
- fn from(value: api_models::payments::GooglePayWalletData) -> Self {
- Self {
- pm_type: value.pm_type,
- description: value.description,
- info: GooglePayPaymentMethodInfo {
- card_network: value.info.card_network,
- card_details: value.info.card_details,
- },
- tokenization_data: GpayTokenizationData {
- token_type: value.tokenization_data.token_type,
- token: value.tokenization_data.token,
- },
- }
- }
-}
-
-impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
- fn from(value: api_models::payments::ApplePayWalletData) -> Self {
- Self {
- payment_data: value.payment_data,
- payment_method: ApplepayPaymentMethod {
- display_name: value.payment_method.display_name,
- network: value.payment_method.network,
- pm_type: value.payment_method.pm_type,
- },
- transaction_identifier: value.transaction_identifier,
- }
- }
-}
-
-impl From<api_models::payments::PayLaterData> for PayLaterData {
- fn from(value: api_models::payments::PayLaterData) -> Self {
- match value {
- api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
- api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
- api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
- api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
- Self::AfterpayClearpayRedirect {}
- }
- api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},
- api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},
- api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},
- api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},
- }
- }
-}
-
-impl From<api_models::payments::BankRedirectData> for BankRedirectData {
- fn from(value: api_models::payments::BankRedirectData) -> Self {
- match value {
- api_models::payments::BankRedirectData::BancontactCard {
- card_number,
- card_exp_month,
- card_exp_year,
- ..
- } => Self::BancontactCard {
- card_number,
- card_exp_month,
- card_exp_year,
- },
- api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
- api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
- api_models::payments::BankRedirectData::Eps { bank_name, .. } => {
- Self::Eps { bank_name }
- }
- api_models::payments::BankRedirectData::Giropay {
- bank_account_bic,
- bank_account_iban,
- ..
- } => Self::Giropay {
- bank_account_bic,
- bank_account_iban,
- },
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
- Self::Ideal { bank_name }
- }
- api_models::payments::BankRedirectData::Interac { .. } => Self::Interac {},
- api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
- Self::OnlineBankingCzechRepublic { issuer }
- }
- api_models::payments::BankRedirectData::OnlineBankingFinland { .. } => {
- Self::OnlineBankingFinland {}
- }
- api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
- Self::OnlineBankingPoland { issuer }
- }
- api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
- Self::OnlineBankingSlovakia { issuer }
- }
- api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => {
- Self::OpenBankingUk { issuer }
- }
- api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
- Self::Przelewy24 { bank_name }
- }
- api_models::payments::BankRedirectData::Sofort {
- preferred_language, ..
- } => Self::Sofort { preferred_language },
- api_models::payments::BankRedirectData::Trustly { .. } => Self::Trustly {},
- api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
- Self::OnlineBankingFpx { issuer }
- }
- api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
- Self::OnlineBankingThailand { issuer }
- }
- }
- }
-}
-
-impl From<api_models::payments::CryptoData> for CryptoData {
- fn from(value: api_models::payments::CryptoData) -> Self {
- let api_models::payments::CryptoData { pay_currency } = value;
- Self { pay_currency }
- }
-}
-
-impl From<api_models::payments::UpiData> for UpiData {
- fn from(value: api_models::payments::UpiData) -> Self {
- let api_models::payments::UpiData { vpa_id } = value;
- Self { vpa_id }
- }
-}
-
-impl From<api_models::payments::VoucherData> for VoucherData {
- fn from(value: api_models::payments::VoucherData) -> Self {
- match value {
- api_models::payments::VoucherData::Boleto(boleto_data) => {
- Self::Boleto(Box::new(BoletoVoucherData {
- social_security_number: boleto_data.social_security_number,
- }))
- }
- api_models::payments::VoucherData::Alfamart(_) => {
- Self::Alfamart(Box::new(AlfamartVoucherData {}))
- }
- api_models::payments::VoucherData::Indomaret(_) => {
- Self::Indomaret(Box::new(IndomaretVoucherData {}))
- }
- api_models::payments::VoucherData::SevenEleven(_)
- | api_models::payments::VoucherData::Lawson(_)
- | api_models::payments::VoucherData::MiniStop(_)
- | api_models::payments::VoucherData::FamilyMart(_)
- | api_models::payments::VoucherData::Seicomart(_)
- | api_models::payments::VoucherData::PayEasy(_) => {
- Self::SevenEleven(Box::new(JCSVoucherData {}))
- }
- api_models::payments::VoucherData::Efecty => Self::Efecty,
- api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
- api_models::payments::VoucherData::RedCompra => Self::RedCompra,
- api_models::payments::VoucherData::RedPagos => Self::RedPagos,
- api_models::payments::VoucherData::Oxxo => Self::Oxxo,
- }
- }
-}
-
-impl From<api_models::payments::GiftCardData> for GiftCardData {
- fn from(value: api_models::payments::GiftCardData) -> Self {
- match value {
- api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
- number: details.number,
- cvc: details.cvc,
- }),
- api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
- }
- }
-}
-
-impl From<api_models::payments::CardToken> for CardToken {
- fn from(value: api_models::payments::CardToken) -> Self {
- let api_models::payments::CardToken {
- card_holder_name,
- card_cvc,
- } = value;
- Self {
- card_holder_name,
- card_cvc,
- }
- }
-}
-
-impl From<api_models::payments::BankDebitData> for BankDebitData {
- fn from(value: api_models::payments::BankDebitData) -> Self {
- match value {
- api_models::payments::BankDebitData::AchBankDebit {
- account_number,
- routing_number,
- bank_name,
- bank_type,
- bank_holder_type,
- ..
- } => Self::AchBankDebit {
- account_number,
- routing_number,
- bank_name,
- bank_type,
- bank_holder_type,
- },
- api_models::payments::BankDebitData::SepaBankDebit { iban, .. } => {
- Self::SepaBankDebit { iban }
- }
- api_models::payments::BankDebitData::BecsBankDebit {
- account_number,
- bsb_number,
- ..
- } => Self::BecsBankDebit {
- account_number,
- bsb_number,
- },
- api_models::payments::BankDebitData::BacsBankDebit {
- account_number,
- sort_code,
- ..
- } => Self::BacsBankDebit {
- account_number,
- sort_code,
- },
- }
- }
-}
-
-impl From<api_models::payments::BankTransferData> for BankTransferData {
- fn from(value: api_models::payments::BankTransferData) -> Self {
- match value {
- api_models::payments::BankTransferData::AchBankTransfer { .. } => {
- Self::AchBankTransfer {}
- }
- api_models::payments::BankTransferData::SepaBankTransfer { .. } => {
- Self::SepaBankTransfer {}
- }
- api_models::payments::BankTransferData::BacsBankTransfer { .. } => {
- Self::BacsBankTransfer {}
- }
- api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
- Self::MultibancoBankTransfer {}
- }
- api_models::payments::BankTransferData::PermataBankTransfer { .. } => {
- Self::PermataBankTransfer {}
- }
- api_models::payments::BankTransferData::BcaBankTransfer { .. } => {
- Self::BcaBankTransfer {}
- }
- api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {
- Self::BniVaBankTransfer {}
- }
- api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {
- Self::BriVaBankTransfer {}
- }
- api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {
- Self::CimbVaBankTransfer {}
- }
- api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
- Self::DanamonVaBankTransfer {}
- }
- api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
- Self::MandiriVaBankTransfer {}
- }
- api_models::payments::BankTransferData::Pix {} => Self::Pix {},
- api_models::payments::BankTransferData::Pse {} => Self::Pse {},
- api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {
- Self::LocalBankTransfer { bank_code }
- }
- }
- }
-}
+pub use hyperswitch_domain_models::payment_method_data::{
+ AliPayQr, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData,
+ BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, CardToken,
+ CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection,
+ GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData,
+ GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection,
+ MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
+ SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, VoucherData, WalletData,
+ WeChatPayQr,
+};
diff --git a/crates/router/src/types/fraud_check.rs b/crates/router/src/types/fraud_check.rs
index 12ab7e4a067..59be546b1c5 100644
--- a/crates/router/src/types/fraud_check.rs
+++ b/crates/router/src/types/fraud_check.rs
@@ -1,11 +1,12 @@
-use common_utils::pii::Email;
+pub use hyperswitch_domain_models::router_request_types::fraud_check::{
+ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
+ FraudCheckSaleData, FraudCheckTransactionData, RefundMethod,
+};
use crate::{
- connector::signifyd::transformers::RefundMethod,
- core::fraud_check::types::FrmFulfillmentRequest,
pii::Serialize,
services,
- types::{self, api, storage_enums, ErrorResponse, ResponseId, RouterData},
+ types::{api, storage_enums, ErrorResponse, ResponseId, RouterData},
};
pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
@@ -13,13 +14,6 @@ pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudChec
pub type FrmSaleType =
dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>;
-#[derive(Debug, Clone)]
-pub struct FraudCheckSaleData {
- pub amount: i64,
- pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
- pub currency: Option<common_enums::Currency>,
- pub email: Option<Email>,
-}
#[derive(Debug, Clone)]
pub struct FrmRouterData {
pub merchant_id: String,
@@ -76,17 +70,6 @@ pub type FrmCheckoutType = dyn services::ConnectorIntegration<
FraudCheckResponseData,
>;
-#[derive(Debug, Clone)]
-pub struct FraudCheckCheckoutData {
- pub amount: i64,
- pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
- pub currency: Option<common_enums::Currency>,
- pub browser_info: Option<types::BrowserInformation>,
- pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
- pub email: Option<Email>,
- pub gateway: Option<String>,
-}
-
pub type FrmTransactionRouterData =
RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>;
@@ -96,19 +79,6 @@ pub type FrmTransactionType = dyn services::ConnectorIntegration<
FraudCheckResponseData,
>;
-#[derive(Debug, Clone)]
-pub struct FraudCheckTransactionData {
- pub amount: i64,
- pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
- pub currency: Option<storage_enums::Currency>,
- pub payment_method: Option<storage_enums::PaymentMethod>,
- pub error_code: Option<String>,
- pub error_message: Option<String>,
- pub connector_transaction_id: Option<String>,
- //The name of the payment gateway or financial institution that processed the transaction.
- pub connector: Option<String>,
-}
-
pub type FrmFulfillmentRouterData =
RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>;
@@ -125,18 +95,3 @@ pub type FrmRecordReturnType = dyn services::ConnectorIntegration<
FraudCheckRecordReturnData,
FraudCheckResponseData,
>;
-
-#[derive(Debug, Clone)]
-pub struct FraudCheckFulfillmentData {
- pub amount: i64,
- pub order_details: Option<Vec<masking::Secret<serde_json::Value>>>,
- pub fulfillment_req: FrmFulfillmentRequest,
-}
-
-#[derive(Debug, Clone)]
-pub struct FraudCheckRecordReturnData {
- pub amount: i64,
- pub currency: Option<storage_enums::Currency>,
- pub refund_method: RefundMethod,
- pub refund_transaction_id: Option<String>,
-}
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 059278a1b1c..62c260de713 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1,7 +1,6 @@
#[cfg(feature = "olap")]
pub mod connector_onboarding;
pub mod currency;
-pub mod custom_serde;
pub mod db_utils;
pub mod ext_traits;
#[cfg(feature = "kv_store")]
diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs
index 03735e61cc7..aeea146df29 100644
--- a/crates/router/src/utils/connector_onboarding.rs
+++ b/crates/router/src/utils/connector_onboarding.rs
@@ -4,7 +4,7 @@ use error_stack::ResultExt;
use super::errors::StorageErrorExt;
use crate::{
consts,
- core::errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult},
+ core::errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
routes::{app::settings, AppState},
types::{self, api::enums},
};
diff --git a/crates/router/src/utils/custom_serde.rs b/crates/router/src/utils/custom_serde.rs
deleted file mode 100644
index dcdad3092b2..00000000000
--- a/crates/router/src/utils/custom_serde.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-pub fn display_serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
-where
- T: std::fmt::Display,
- S: serde::ser::Serializer,
-{
- serializer.serialize_str(&format!("{}", value))
-}
diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml
index b98f212d674..73832a1ad6a 100644
--- a/crates/scheduler/Cargo.toml
+++ b/crates/scheduler/Cargo.toml
@@ -7,7 +7,7 @@ license.workspace = true
[features]
default = ["kv_store", "olap"]
-olap = ["storage_impl/olap"]
+olap = ["storage_impl/olap", "hyperswitch_domain_models/olap"]
kv_store = []
email = ["external_services/email"]
@@ -35,6 +35,7 @@ masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
+hyperswitch_domain_models = {version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
# [[bin]]
# name = "scheduler"
diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs
index e4fd56ba8d2..e630287c316 100644
--- a/crates/scheduler/src/errors.rs
+++ b/crates/scheduler/src/errors.rs
@@ -1,6 +1,7 @@
pub use common_utils::errors::{ParsingError, ValidationError};
#[cfg(feature = "email")]
use external_services::email::EmailError;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
pub use redis_interface::errors::RedisError;
pub use storage_impl::errors::ApplicationError;
use storage_impl::errors::StorageError;
@@ -88,6 +89,12 @@ impl<T: PTError> From<T> for ProcessTrackerError {
}
}
+impl PTError for ApiErrorResponse {
+ fn to_pt_error(&self) -> ProcessTrackerError {
+ ProcessTrackerError::EApiErrorResponse
+ }
+}
+
impl<T: PTError + std::fmt::Debug + std::fmt::Display> From<error_stack::Report<T>>
for ProcessTrackerError
{
|
chore
|
move RouterData Request types to hyperswitch_domain_models crate (#4723)
|
9b57e6c4ac518ff124a510dd0d9872ac022f165b
|
2025-01-15 13:41:35
|
Debarati Ghatak
|
ci: update cypress creds for Novalnet (#7035)
| false
|
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index 070682b9c3a..c4a4a326c69 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -128,7 +128,7 @@ jobs:
CONNECTOR_AUTH_PASSPHRASE: ${{ secrets.CONNECTOR_AUTH_PASSPHRASE }}
CONNECTOR_CREDS_S3_BUCKET_URI: ${{ secrets.CONNECTOR_CREDS_S3_BUCKET_URI}}
DESTINATION_FILE_NAME: "creds.json.gpg"
- S3_SOURCE_FILE_NAME: "aa328308-b34e-41b7-a590-4fe45cfe7991.json.gpg"
+ S3_SOURCE_FILE_NAME: "ae17cddf-4e13-471e-a78d-58eafcfd66a5.json.gpg"
shell: bash
run: |
mkdir -p ".github/secrets" ".github/test"
|
ci
|
update cypress creds for Novalnet (#7035)
|
58105d4ae2eedea137c179c91775e5ec5524897a
|
2023-08-30 22:45:16
|
Hudson C. Dalprá
|
docs(CONTRIBUTING): fix open a discussion link (#2054)
| false
|
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 40d5eb052b7..cb5206a2545 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -86,7 +86,7 @@ having problems, you can [open a discussion] asking for help.
In exchange for receiving help, we ask that you contribute back a documentation
PR that helps others avoid the problems that you encountered.
-[open a discussion]: https://github.com/juspay/hyperswitch/discussions/new
+[open a discussion]: https://github.com/juspay/hyperswitch/discussions/new/choose
### Submitting a Bug Report
|
docs
|
fix open a discussion link (#2054)
|
7d73e9095a532aa5c2bb4bf8806fc678460cf8d4
|
2024-11-14 14:10:41
|
Kartikeya Hegde
|
feat: implement scylla traits for StrongSecret (#6500)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 7c9cb19d5c9..27b4158ba61 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3699,6 +3699,12 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "histogram"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12cb882ccb290b8646e554b157ab0b71e64e8d5bef775cd66b6531e52d302669"
+
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -4310,6 +4316,15 @@ dependencies = [
"either",
]
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.11"
@@ -4567,6 +4582,15 @@ dependencies = [
"linked-hash-map",
]
+[[package]]
+name = "lz4_flex"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75761162ae2b0e580d7e7c390558127e5f01b4194debd6221fd8c207fc80e3f5"
+dependencies = [
+ "twox-hash",
+]
+
[[package]]
name = "masking"
version = "0.1.0"
@@ -4574,6 +4598,7 @@ dependencies = [
"bytes 1.7.1",
"diesel",
"erased-serde 0.4.5",
+ "scylla",
"serde",
"serde_json",
"subtle",
@@ -5971,6 +5996,15 @@ dependencies = [
"getrandom",
]
+[[package]]
+name = "rand_pcg"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e"
+dependencies = [
+ "rand_core",
+]
+
[[package]]
name = "rand_xorshift"
version = "0.3.0"
@@ -6892,6 +6926,66 @@ dependencies = [
"untrusted 0.9.0",
]
+[[package]]
+name = "scylla"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8139623d3fb0c8205b15e84fa587f3aa0ba61f876c19a9157b688f7c1763a7c5"
+dependencies = [
+ "arc-swap",
+ "async-trait",
+ "byteorder",
+ "bytes 1.7.1",
+ "chrono",
+ "dashmap",
+ "futures 0.3.30",
+ "hashbrown 0.14.5",
+ "histogram",
+ "itertools 0.13.0",
+ "lazy_static",
+ "lz4_flex",
+ "rand",
+ "rand_pcg",
+ "scylla-cql",
+ "scylla-macros",
+ "smallvec 1.13.2",
+ "snap",
+ "socket2",
+ "thiserror",
+ "tokio 1.40.0",
+ "tracing",
+ "uuid",
+]
+
+[[package]]
+name = "scylla-cql"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de7020bcd1f6fdbeaed356cd426bf294b2071bd7120d48d2e8e319295e2acdcd"
+dependencies = [
+ "async-trait",
+ "byteorder",
+ "bytes 1.7.1",
+ "lz4_flex",
+ "scylla-macros",
+ "snap",
+ "thiserror",
+ "tokio 1.40.0",
+ "uuid",
+]
+
+[[package]]
+name = "scylla-macros"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3859b6938663fc5062e3b26f3611649c9bd26fb252e85f6fdfa581e0d2ce74b6"
+dependencies = [
+ "darling 0.20.10",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.77",
+]
+
[[package]]
name = "sdd"
version = "3.0.2"
@@ -7315,6 +7409,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "snap"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b"
+
[[package]]
name = "socket2"
version = "0.5.7"
@@ -7569,6 +7669,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
[[package]]
name = "storage_impl"
version = "0.1.0"
@@ -8670,6 +8776,16 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "twox-hash"
+version = "1.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675"
+dependencies = [
+ "cfg-if 1.0.0",
+ "static_assertions",
+]
+
[[package]]
name = "typeid"
version = "1.0.2"
diff --git a/crates/masking/Cargo.toml b/crates/masking/Cargo.toml
index ed20a08de34..425c1ca36ec 100644
--- a/crates/masking/Cargo.toml
+++ b/crates/masking/Cargo.toml
@@ -12,6 +12,7 @@ default = ["alloc", "serde", "diesel", "time"]
alloc = ["zeroize/alloc"]
serde = ["dep:serde", "dep:serde_json"]
time = ["dep:time"]
+cassandra = ["dep:scylla"]
[package.metadata.docs.rs]
all-features = true
@@ -27,6 +28,7 @@ subtle = "2.5.0"
time = { version = "0.3.35", optional = true, features = ["serde-human-readable"] }
url = { version = "2.5.0", features = ["serde"] }
zeroize = { version = "1.7", default-features = false }
+scylla = { version = "0.14.0", optional = true}
[dev-dependencies]
serde_json = "1.0.115"
diff --git a/crates/masking/src/cassandra.rs b/crates/masking/src/cassandra.rs
new file mode 100644
index 00000000000..dc81512e79d
--- /dev/null
+++ b/crates/masking/src/cassandra.rs
@@ -0,0 +1,50 @@
+use scylla::{
+ cql_to_rust::FromCqlVal,
+ deserialize::DeserializeValue,
+ frame::response::result::{ColumnType, CqlValue},
+ serialize::{
+ value::SerializeValue,
+ writers::{CellWriter, WrittenCellProof},
+ SerializationError,
+ },
+};
+
+use crate::{abs::PeekInterface, StrongSecret};
+
+impl<T> SerializeValue for StrongSecret<T>
+where
+ T: SerializeValue + zeroize::Zeroize + Clone,
+{
+ fn serialize<'b>(
+ &self,
+ typ: &ColumnType,
+ writer: CellWriter<'b>,
+ ) -> Result<WrittenCellProof<'b>, SerializationError> {
+ self.peek().serialize(typ, writer)
+ }
+}
+
+impl<'frame, T> DeserializeValue<'frame> for StrongSecret<T>
+where
+ T: DeserializeValue<'frame> + zeroize::Zeroize + Clone,
+{
+ fn type_check(typ: &ColumnType) -> Result<(), scylla::deserialize::TypeCheckError> {
+ T::type_check(typ)
+ }
+
+ fn deserialize(
+ typ: &'frame ColumnType,
+ v: Option<scylla::deserialize::FrameSlice<'frame>>,
+ ) -> Result<Self, scylla::deserialize::DeserializationError> {
+ Ok(Self::new(T::deserialize(typ, v)?))
+ }
+}
+
+impl<T> FromCqlVal<CqlValue> for StrongSecret<T>
+where
+ T: FromCqlVal<CqlValue> + zeroize::Zeroize + Clone,
+{
+ fn from_cql(cql_val: CqlValue) -> Result<Self, scylla::cql_to_rust::FromCqlValError> {
+ Ok(Self::new(T::from_cql(cql_val)?))
+ }
+}
diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs
index ca0da6b6767..d376e935bd6 100644
--- a/crates/masking/src/lib.rs
+++ b/crates/masking/src/lib.rs
@@ -57,6 +57,9 @@ pub mod prelude {
#[cfg(feature = "diesel")]
mod diesel;
+#[cfg(feature = "cassandra")]
+mod cassandra;
+
pub mod maskable;
pub use maskable::*;
|
feat
|
implement scylla traits for StrongSecret (#6500)
|
6944415da14cda3e9d5fbef62805d7b18d64eacf
|
2023-06-21 21:32:33
|
Narayan Bhat
|
fix: add requires_customer_action status to payment confirm (#1500)
| false
|
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 513edfaf1fc..454084c1a6d 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -66,6 +66,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
+ storage_enums::IntentStatus::RequiresCustomerAction,
],
"confirm",
)?;
|
fix
|
add requires_customer_action status to payment confirm (#1500)
|
30c14019d067ad5f105563f205eb1941010233e8
|
2023-12-19 20:11:31
|
Sakil Mostak
|
feat(connector): [NMI] Implement webhook for Payments and Refunds (#3164)
| false
|
diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs
index df903ddd8a3..0c01c752039 100644
--- a/crates/router/src/connector/nmi.rs
+++ b/crates/router/src/connector/nmi.rs
@@ -2,9 +2,10 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{ext_traits::ByteSliceExt, request::RequestContent};
+use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
use diesel_models::enums;
use error_stack::{IntoReport, ResultExt};
+use regex::Regex;
use transformers as nmi;
use super::utils as connector_utils;
@@ -15,6 +16,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
+ transformers::ForeignFrom,
ErrorResponse,
},
};
@@ -94,6 +96,14 @@ impl ConnectorValidation for Nmi {
),
}
}
+
+ fn validate_psync_reference_id(
+ &self,
+ _data: &types::PaymentsSyncRouterData,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ // in case we dont have transaction id, we can make psync using attempt id
+ Ok(())
+ }
}
impl
@@ -784,24 +794,124 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
#[async_trait::async_trait]
impl api::IncomingWebhook for Nmi {
- fn get_webhook_object_reference_id(
+ fn get_webhook_source_verification_algorithm(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
+ Ok(Box::new(crypto::HmacSha256))
+ }
+
+ fn get_webhook_source_verification_signature(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let sig_header =
+ connector_utils::get_header_key_value("webhook-signature", request.headers)?;
+
+ let regex_pattern = r"t=(.*),s=(.*)";
+
+ if let Some(captures) = Regex::new(regex_pattern)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?
+ .captures(sig_header)
+ {
+ let signature = captures
+ .get(1)
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)
+ .into_report()?
+ .as_str();
+ return Ok(signature.as_bytes().to_vec());
+ }
+
+ Err(errors::ConnectorError::WebhookSignatureNotFound).into_report()
+ }
+
+ fn get_webhook_source_verification_message(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ _merchant_id: &str,
+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let sig_header =
+ connector_utils::get_header_key_value("webhook-signature", request.headers)?;
+
+ let regex_pattern = r"t=(.*),s=(.*)";
+
+ if let Some(captures) = Regex::new(regex_pattern)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?
+ .captures(sig_header)
+ {
+ let nonce = captures
+ .get(0)
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)
+ .into_report()?
+ .as_str();
+
+ let message = format!("{}.{}", nonce, String::from_utf8_lossy(request.body));
+
+ return Ok(message.into_bytes());
+ }
+ Err(errors::ConnectorError::WebhookSignatureNotFound).into_report()
+ }
+
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
- Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ let reference_body: nmi::NmiWebhookObjectReference = request
+ .body
+ .parse_struct("nmi NmiWebhookObjectReference")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ let object_reference_id = match reference_body.event_body.action.action_type {
+ nmi::NmiActionType::Sale => api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::PaymentAttemptId(
+ reference_body.event_body.order_id,
+ ),
+ ),
+ nmi::NmiActionType::Refund => api_models::webhooks::ObjectReferenceId::RefundId(
+ api_models::webhooks::RefundIdType::RefundId(reference_body.event_body.order_id),
+ ),
+ _ => Err(errors::ConnectorError::WebhooksNotImplemented).into_report()?,
+ };
+
+ Ok(object_reference_id)
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ let event_type_body: nmi::NmiWebhookEventBody = request
+ .body
+ .parse_struct("nmi NmiWebhookEventType")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ Ok(api::IncomingWebhookEvent::foreign_from(
+ event_type_body.event_type,
+ ))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
- Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ let webhook_body: nmi::NmiWebhookBody = request
+ .body
+ .parse_struct("nmi NmiWebhookBody")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ match webhook_body.event_body.action.action_type {
+ nmi::NmiActionType::Sale
+ | nmi::NmiActionType::Auth
+ | nmi::NmiActionType::Capture
+ | nmi::NmiActionType::Void
+ | nmi::NmiActionType::Credit => {
+ Ok(Box::new(nmi::SyncResponse::try_from(&webhook_body)?))
+ }
+ nmi::NmiActionType::Refund => Ok(Box::new(webhook_body)),
+ }
}
}
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 5dfcdcf8b99..6146f4a4599 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -1,3 +1,4 @@
+use api_models::webhooks;
use cards::CardNumber;
use common_utils::{errors::CustomResult, ext_traits::XmlExt};
use error_stack::{IntoReport, Report, ResultExt};
@@ -319,9 +320,7 @@ impl
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.transactionid,
- ),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.orderid),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -544,7 +543,7 @@ impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest {
#[derive(Debug, Serialize)]
pub struct NmiSyncRequest {
- pub transaction_id: String,
+ pub order_id: String,
pub security_key: Secret<String>,
}
@@ -554,11 +553,7 @@ impl TryFrom<&types::PaymentsSyncRouterData> for NmiSyncRequest {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
security_key: auth.api_key,
- transaction_id: item
- .request
- .connector_transaction_id
- .get_connector_transaction_id()
- .change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
+ order_id: item.attempt_id.clone(),
})
}
}
@@ -889,6 +884,19 @@ impl TryFrom<Vec<u8>> for SyncResponse {
}
}
+impl TryFrom<Vec<u8>> for NmiRefundSyncResponse {
+ type Error = Error;
+ fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
+ let query_response = String::from_utf8(bytes)
+ .into_report()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ query_response
+ .parse_xml::<Self>()
+ .into_report()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ }
+}
+
impl From<NmiStatus> for enums::AttemptStatus {
fn from(item: NmiStatus) -> Self {
match item {
@@ -909,6 +917,7 @@ pub struct NmiRefundRequest {
transaction_type: TransactionType,
security_key: Secret<String>,
transactionid: String,
+ orderid: String,
amount: f64,
}
@@ -920,6 +929,7 @@ impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundReque
transaction_type: TransactionType::Refund,
security_key: auth_type.api_key,
transactionid: item.router_data.request.connector_transaction_id.clone(),
+ orderid: item.router_data.request.refund_id.clone(),
amount: item.amount,
})
}
@@ -935,7 +945,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>>
let refund_status = enums::RefundStatus::from(item.response.response);
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.transactionid,
+ connector_refund_id: item.response.orderid,
refund_status,
}),
..item.data
@@ -974,15 +984,14 @@ impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest {
type Error = Error;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
- let transaction_id = item
- .request
- .connector_refund_id
- .clone()
- .ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(Self {
security_key: auth.api_key,
- transaction_id,
+ order_id: item
+ .request
+ .connector_refund_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
})
}
}
@@ -994,12 +1003,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, types::Response>>
fn try_from(
item: types::RefundsResponseRouterData<api::RSync, types::Response>,
) -> Result<Self, Self::Error> {
- let response = SyncResponse::try_from(item.response.response.to_vec())?;
+ let response = NmiRefundSyncResponse::try_from(item.response.response.to_vec())?;
let refund_status =
enums::RefundStatus::from(NmiStatus::from(response.transaction.condition));
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: response.transaction.transaction_id,
+ connector_refund_id: response.transaction.order_id,
refund_status,
}),
..item.data
@@ -1036,13 +1045,137 @@ impl From<String> for NmiStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct SyncTransactionResponse {
- transaction_id: String,
+ pub transaction_id: String,
+ pub condition: String,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct SyncResponse {
+ pub transaction: SyncTransactionResponse,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct RefundSyncBody {
+ order_id: String,
condition: String,
}
#[derive(Debug, Deserialize)]
-struct SyncResponse {
- transaction: SyncTransactionResponse,
+struct NmiRefundSyncResponse {
+ transaction: RefundSyncBody,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NmiWebhookObjectReference {
+ pub event_body: NmiReferenceBody,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NmiReferenceBody {
+ pub order_id: String,
+ pub action: NmiActionBody,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct NmiActionBody {
+ pub action_type: NmiActionType,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum NmiActionType {
+ Auth,
+ Capture,
+ Credit,
+ Refund,
+ Sale,
+ Void,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NmiWebhookEventBody {
+ pub event_type: NmiWebhookEventType,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub enum NmiWebhookEventType {
+ #[serde(rename = "transaction.sale.success")]
+ SaleSuccess,
+ #[serde(rename = "transaction.sale.failure")]
+ SaleFailure,
+ #[serde(rename = "transaction.sale.unknown")]
+ SaleUnknown,
+ #[serde(rename = "transaction.auth.success")]
+ AuthSuccess,
+ #[serde(rename = "transaction.auth.failure")]
+ AuthFailure,
+ #[serde(rename = "transaction.auth.unknown")]
+ AuthUnknown,
+ #[serde(rename = "transaction.refund.success")]
+ RefundSuccess,
+ #[serde(rename = "transaction.refund.failure")]
+ RefundFailure,
+ #[serde(rename = "transaction.refund.unknown")]
+ RefundUnknown,
+ #[serde(rename = "transaction.void.success")]
+ VoidSuccess,
+ #[serde(rename = "transaction.void.failure")]
+ VoidFailure,
+ #[serde(rename = "transaction.void.unknown")]
+ VoidUnknown,
+ #[serde(rename = "transaction.capture.success")]
+ CaptureSuccess,
+ #[serde(rename = "transaction.capture.failure")]
+ CaptureFailure,
+ #[serde(rename = "transaction.capture.unknown")]
+ CaptureUnknown,
+}
+
+impl ForeignFrom<NmiWebhookEventType> for webhooks::IncomingWebhookEvent {
+ fn foreign_from(status: NmiWebhookEventType) -> Self {
+ match status {
+ NmiWebhookEventType::SaleSuccess => Self::PaymentIntentSuccess,
+ NmiWebhookEventType::SaleFailure => Self::PaymentIntentFailure,
+ NmiWebhookEventType::RefundSuccess => Self::RefundSuccess,
+ NmiWebhookEventType::RefundFailure => Self::RefundFailure,
+ NmiWebhookEventType::VoidSuccess => Self::PaymentIntentCancelled,
+ NmiWebhookEventType::SaleUnknown
+ | NmiWebhookEventType::RefundUnknown
+ | NmiWebhookEventType::AuthSuccess
+ | NmiWebhookEventType::AuthFailure
+ | NmiWebhookEventType::AuthUnknown
+ | NmiWebhookEventType::VoidFailure
+ | NmiWebhookEventType::VoidUnknown
+ | NmiWebhookEventType::CaptureSuccess
+ | NmiWebhookEventType::CaptureFailure
+ | NmiWebhookEventType::CaptureUnknown => Self::EventNotSupported,
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct NmiWebhookBody {
+ pub event_body: NmiWebhookObject,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct NmiWebhookObject {
+ pub transaction_id: String,
+ pub order_id: String,
+ pub condition: String,
+ pub action: NmiActionBody,
+}
+
+impl TryFrom<&NmiWebhookBody> for SyncResponse {
+ type Error = Error;
+ fn try_from(item: &NmiWebhookBody) -> Result<Self, Self::Error> {
+ let transaction = SyncTransactionResponse {
+ transaction_id: item.event_body.transaction_id.to_owned(),
+ condition: item.event_body.condition.to_owned(),
+ };
+
+ Ok(Self { transaction })
+ }
}
|
feat
|
[NMI] Implement webhook for Payments and Refunds (#3164)
|
e7579a4819358001768d2c6a5b04e10f8810e24f
|
2022-12-24 14:28:03
|
Sanchith Hegde
|
chore: add lints in workspace cargo config (#223)
| false
|
diff --git a/.cargo/config.toml b/.cargo/config.toml
index 1368506f4eb..66da12a13b1 100644
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,2 +1,23 @@
+[target.'cfg(all())']
+rustflags = [
+ "-Funsafe_code",
+ "-Wclippy::as_conversions",
+ "-Wclippy::expect_used",
+ "-Wclippy::missing_panics_doc",
+ "-Wclippy::panic_in_result_fn",
+ "-Wclippy::panic",
+ "-Wclippy::panicking_unwrap",
+ "-Wclippy::todo",
+ "-Wclippy::unimplemented",
+ "-Wclippy::unreachable",
+ "-Wclippy::unwrap_in_result",
+ "-Wclippy::unwrap_used",
+ "-Wclippy::use_self",
+ # "-Wmissing_debug_implementations",
+ # "-Wmissing_docs",
+ "-Wrust_2018_idioms",
+ "-Wunused_qualifications",
+]
+
[alias]
-gen-pg = "generate --path ../../../../connector-template -n"
\ No newline at end of file
+gen-pg = "generate --path ../../../../connector-template -n"
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml
index ab6fce7dba4..32e0767576b 100644
--- a/.github/workflows/CI.yml
+++ b/.github/workflows/CI.yml
@@ -30,7 +30,6 @@ concurrency:
cancel-in-progress: true
env:
- RUSTFLAGS: "-D warnings"
# Disable incremental compilation.
#
# Incremental compilation is useful as part of an edit-build-test-edit cycle,
@@ -104,6 +103,10 @@ jobs:
with:
crate: cargo-hack
+ - name: Deny warnings
+ shell: bash
+ run: sed -i 's/rustflags = \[/rustflags = \[\n "-Dwarnings",/' .cargo/config.toml
+
- name: Test compilation
shell: bash
run: cargo hack check --workspace --each-feature --no-dev-deps
@@ -176,6 +179,10 @@ jobs:
# mkdir -p .cargo
# curl -sL https://raw.githubusercontent.com/EmbarkStudios/rust-ecosystem/main/lints.toml >> .cargo/config.toml
+ - name: Deny warnings
+ shell: bash
+ run: sed -i 's/rustflags = \[/rustflags = \[\n "-Dwarnings",/' .cargo/config.toml
+
- name: Run clippy
shell: bash
run: cargo clippy --all-features --all-targets
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 791d304dcaf..e37de90ba7e 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -501,13 +501,13 @@ pub enum Connector {
impl From<AttemptStatus> for IntentStatus {
fn from(s: AttemptStatus) -> Self {
match s {
- AttemptStatus::Charged | AttemptStatus::AutoRefunded => IntentStatus::Succeeded,
+ AttemptStatus::Charged | AttemptStatus::AutoRefunded => Self::Succeeded,
- AttemptStatus::ConfirmationAwaited => IntentStatus::RequiresConfirmation,
- AttemptStatus::PaymentMethodAwaited => IntentStatus::RequiresPaymentMethod,
+ AttemptStatus::ConfirmationAwaited => Self::RequiresConfirmation,
+ AttemptStatus::PaymentMethodAwaited => Self::RequiresPaymentMethod,
- AttemptStatus::Authorized => IntentStatus::RequiresCapture,
- AttemptStatus::AuthenticationPending => IntentStatus::RequiresCustomerAction,
+ AttemptStatus::Authorized => Self::RequiresCapture,
+ AttemptStatus::AuthenticationPending => Self::RequiresCustomerAction,
AttemptStatus::PartialCharged
| AttemptStatus::Started
@@ -516,15 +516,15 @@ impl From<AttemptStatus> for IntentStatus {
| AttemptStatus::CodInitiated
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
- | AttemptStatus::Pending => IntentStatus::Processing,
+ | AttemptStatus::Pending => Self::Processing,
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::VoidFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::CaptureFailed
- | AttemptStatus::Failure => IntentStatus::Failed,
- AttemptStatus::Voided => IntentStatus::Cancelled,
+ | AttemptStatus::Failure => Self::Failed,
+ AttemptStatus::Voided => Self::Cancelled,
}
}
}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index a087d673681..5db1f91f127 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -86,7 +86,7 @@ impl<'de> serde::Deserialize<'de> for ListPaymentMethodRequest {
impl<'de> de::Visitor<'de> for FieldVisitor {
type Value = ListPaymentMethodRequest;
- fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Failed while deserializing as map")
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 1a884d56713..76916d7eb11 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -77,7 +77,7 @@ impl From<Amount> for i64 {
impl From<i64> for Amount {
fn from(val: i64) -> Self {
- NonZeroI64::new(val).map_or(Amount::Zero, Amount::Value)
+ NonZeroI64::new(val).map_or(Self::Zero, Amount::Value)
}
}
@@ -241,10 +241,11 @@ pub enum PayLaterData {
},
}
-#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+#[derive(Debug, Clone, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize)]
pub enum PaymentMethod {
#[serde(rename(deserialize = "card"))]
Card(CCard),
+ #[default]
#[serde(rename(deserialize = "bank_transfer"))]
BankTransfer,
#[serde(rename(deserialize = "wallet"))]
@@ -279,12 +280,6 @@ pub enum PaymentMethodDataResponse {
Paypal,
}
-impl Default for PaymentMethod {
- fn default() -> Self {
- PaymentMethod::BankTransfer
- }
-}
-
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PaymentIdType {
PaymentIntentId(String),
@@ -683,13 +678,11 @@ impl From<CCard> for CCardResponse {
impl From<PaymentMethod> for PaymentMethodDataResponse {
fn from(payment_method_data: PaymentMethod) -> Self {
match payment_method_data {
- PaymentMethod::Card(card) => PaymentMethodDataResponse::Card(CCardResponse::from(card)),
- PaymentMethod::BankTransfer => PaymentMethodDataResponse::BankTransfer,
- PaymentMethod::PayLater(pay_later_data) => {
- PaymentMethodDataResponse::PayLater(pay_later_data)
- }
- PaymentMethod::Wallet(wallet_data) => PaymentMethodDataResponse::Wallet(wallet_data),
- PaymentMethod::Paypal => PaymentMethodDataResponse::Paypal,
+ PaymentMethod::Card(card) => Self::Card(CCardResponse::from(card)),
+ PaymentMethod::BankTransfer => Self::BankTransfer,
+ PaymentMethod::PayLater(pay_later_data) => Self::PayLater(pay_later_data),
+ PaymentMethod::Wallet(wallet_data) => Self::Wallet(wallet_data),
+ PaymentMethod::Paypal => Self::Paypal,
}
}
}
@@ -873,7 +866,7 @@ mod payment_id_type {
impl<'de> Visitor<'de> for PaymentIdVisitor {
type Value = PaymentIdType;
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("payment id")
}
@@ -888,7 +881,7 @@ mod payment_id_type {
impl<'de> Visitor<'de> for OptionalPaymentIdVisitor {
type Value = Option<PaymentIdType>;
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("payment id")
}
@@ -944,7 +937,7 @@ mod amount {
impl<'de> de::Visitor<'de> for AmountVisitor {
type Value = Amount;
- fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "amount as integer")
}
@@ -952,13 +945,24 @@ mod amount {
where
E: de::Error,
{
- self.visit_i64(v as i64)
+ let v = i64::try_from(v).map_err(|_| {
+ E::custom(format!(
+ "invalid value `{v}`, expected an integer between 0 and {}",
+ i64::MAX
+ ))
+ })?;
+ self.visit_i64(v)
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
+ if v.is_negative() {
+ return Err(E::custom(format!(
+ "invalid value `{v}`, expected a positive integer"
+ )));
+ }
Ok(Amount::from(v))
}
}
@@ -966,7 +970,7 @@ mod amount {
impl<'de> de::Visitor<'de> for OptionalAmountVisitor {
type Value = Option<Amount>;
- fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "option of amount (as integer)")
}
@@ -1002,6 +1006,7 @@ mod amount {
#[cfg(test)]
mod tests {
+ #![allow(clippy::unwrap_used)]
use super::*;
#[test]
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index 77288eccfa3..14abcc9f9d7 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -34,30 +34,23 @@ pub struct RefundResponse {
pub error_message: Option<String>,
}
-#[derive(Debug, Eq, Clone, PartialEq, Deserialize, Serialize)]
+#[derive(Debug, Eq, Clone, PartialEq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
Succeeded,
Failed,
+ #[default]
Pending,
Review,
}
-impl Default for RefundStatus {
- fn default() -> Self {
- RefundStatus::Pending
- }
-}
-
impl From<enums::RefundStatus> for RefundStatus {
fn from(status: enums::RefundStatus) -> Self {
match status {
- enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => {
- RefundStatus::Failed
- }
- enums::RefundStatus::ManualReview => RefundStatus::Review,
- enums::RefundStatus::Pending => RefundStatus::Pending,
- enums::RefundStatus::Success => RefundStatus::Succeeded,
+ enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed,
+ enums::RefundStatus::ManualReview => Self::Review,
+ enums::RefundStatus::Pending => Self::Pending,
+ enums::RefundStatus::Success => Self::Succeeded,
}
}
}
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs
index 808381cd3ed..76162a12d77 100644
--- a/crates/common_utils/src/ext_traits.rs
+++ b/crates/common_utils/src/ext_traits.rs
@@ -26,7 +26,7 @@ where
fn convert_and_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
- Result<P, <P as TryFrom<&'e Self>>::Error>: error_stack::ResultExt,
+ Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
///
@@ -37,7 +37,7 @@ where
fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
- Result<P, <P as TryFrom<&'e Self>>::Error>: error_stack::ResultExt,
+ Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
///
@@ -68,7 +68,7 @@ where
///
/// Functionality, for specifically encoding `Self` into `Vec<u8>`
/// after serialization by using `serde::Serialize`
- ///
+ ///
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize;
@@ -81,7 +81,7 @@ where
fn convert_and_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
- Result<P, <P as TryFrom<&'e Self>>::Error>: error_stack::ResultExt,
+ Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_json::to_string(&P::try_from(self).change_context(errors::ParsingError)?)
@@ -93,7 +93,7 @@ where
fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
- Result<P, <P as TryFrom<&'e Self>>::Error>: error_stack::ResultExt,
+ Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_urlencoded::to_string(&P::try_from(self).change_context(errors::ParsingError)?)
@@ -303,7 +303,7 @@ pub trait AsyncExt<A, B> {
}
#[async_trait::async_trait]
-impl<A: std::marker::Send, B, E: std::marker::Send> AsyncExt<A, B> for Result<A, E> {
+impl<A: Send, B, E: Send> AsyncExt<A, B> for Result<A, E> {
type WrappedSelf<T> = Result<T, E>;
async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
@@ -329,7 +329,7 @@ impl<A: std::marker::Send, B, E: std::marker::Send> AsyncExt<A, B> for Result<A,
}
#[async_trait::async_trait]
-impl<A: std::marker::Send, B> AsyncExt<A, B> for Option<A> {
+impl<A: Send, B> AsyncExt<A, B> for Option<A> {
type WrappedSelf<T> = Option<T>;
async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index 2329ddb3756..8ba8aa195a5 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -1,18 +1,5 @@
#![forbid(unsafe_code)]
-#![warn(
- missing_docs,
- rust_2018_idioms,
- missing_debug_implementations,
- clippy::expect_used,
- clippy::missing_panics_doc,
- clippy::panic,
- clippy::panic_in_result_fn,
- clippy::panicking_unwrap,
- clippy::unreachable,
- clippy::unwrap_in_result,
- clippy::unwrap_used,
- clippy::unimplemented
-)]
+#![warn(missing_docs, missing_debug_implementations)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
pub mod consts;
diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs
index 209c7e01c11..74d2c205969 100644
--- a/crates/drainer/src/connection.rs
+++ b/crates/drainer/src/connection.rs
@@ -1,4 +1,3 @@
-use async_bb8_diesel::ConnectionManager;
use bb8::PooledConnection;
use diesel::PgConnection;
@@ -27,7 +26,9 @@ pub async fn diesel_make_pg_pool(database: &Database, _test_transaction: bool) -
}
#[allow(clippy::expect_used)]
-pub async fn pg_connection(pool: &PgPool) -> PooledConnection<ConnectionManager<PgConnection>> {
+pub async fn pg_connection(
+ pool: &PgPool,
+) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {
pool.get()
.await
.expect("Couldn't retrieve PostgreSQL connection")
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index a11b374d9bf..23db8e4bce2 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -100,7 +100,10 @@ async fn drainer(
macro_util::handle_resp!(a.orig.update(&conn, a.update_data).await, "up", "ref")
}
},
- kv::DBOperation::Delete => todo!(),
+ kv::DBOperation::Delete => {
+ // TODO: Implement this
+ println!("Not implemented!");
+ }
};
}
diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs
index 739d7c6448b..44755443342 100644
--- a/crates/drainer/src/main.rs
+++ b/crates/drainer/src/main.rs
@@ -5,7 +5,10 @@ use structopt::StructOpt;
async fn main() -> DrainerResult<()> {
// Get configuration
let cmd_line = settings::CmdLineConf::from_args();
- let conf = settings::Settings::with_config_path(cmd_line.config_path).unwrap();
+
+ #[allow(clippy::expect_used)]
+ let conf = settings::Settings::with_config_path(cmd_line.config_path)
+ .expect("Unable to construct application configuration");
let store = services::Store::new(&conf, false).await;
let store = std::sync::Arc::new(store);
diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs
index f9675727662..d0452d5c5bc 100644
--- a/crates/masking/src/lib.rs
+++ b/crates/masking/src/lib.rs
@@ -1,20 +1,7 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
#![forbid(unsafe_code)]
-#![warn(
- missing_docs,
- rust_2018_idioms,
- unused_qualifications,
- clippy::expect_used,
- clippy::missing_panics_doc,
- clippy::panic,
- clippy::panic_in_result_fn,
- clippy::panicking_unwrap,
- clippy::unreachable,
- clippy::unwrap_in_result,
- clippy::unwrap_used,
- clippy::use_self
-)]
+#![warn(missing_docs)]
//!
//! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped.
diff --git a/crates/masking/tests/basic.rs b/crates/masking/tests/basic.rs
index 32f4bbedbf7..59bb2cefaa4 100644
--- a/crates/masking/tests/basic.rs
+++ b/crates/masking/tests/basic.rs
@@ -1,4 +1,4 @@
-#![allow(dead_code)]
+#![allow(dead_code, clippy::unwrap_used, clippy::panic_in_result_fn)]
use masking as pii;
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index 7e733473df6..58d61225221 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -75,7 +75,7 @@ impl super::RedisConnectionPool {
let serialized = Encode::<V>::encode_to_vec(&value)
.change_context(errors::RedisError::JsonSerializationFailed)?;
- self.set_key(key, &serialized as &[u8]).await
+ self.set_key(key, serialized.as_slice()).await
}
#[instrument(level = "DEBUG", skip(self))]
@@ -242,7 +242,7 @@ impl super::RedisConnectionPool {
let serialized = Encode::<V>::encode_to_vec(&value)
.change_context(errors::RedisError::JsonSerializationFailed)?;
- self.set_hash_field_if_not_exist(key, field, &serialized as &[u8])
+ self.set_hash_field_if_not_exist(key, field, serialized.as_slice())
.await
}
@@ -561,6 +561,7 @@ impl super::RedisConnectionPool {
#[cfg(test)]
mod tests {
+ #![allow(clippy::unwrap_used)]
use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings};
diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs
index fec2f9d1e12..3a0c4164a1e 100644
--- a/crates/redis_interface/src/lib.rs
+++ b/crates/redis_interface/src/lib.rs
@@ -38,7 +38,7 @@ impl RedisConnectionPool {
///
/// Panics if a connection to Redis is not successful.
#[allow(clippy::expect_used)]
- pub async fn new(conf: &types::RedisSettings) -> Self {
+ pub async fn new(conf: &RedisSettings) -> Self {
let redis_connection_url = match conf.cluster_enabled {
// Fred relies on this format for specifying cluster where the host port is ignored & only query parameters are used for node addresses
// redis-cluster://username:password@host:port?node=bar.com:30002&node=baz.com:30003
@@ -100,8 +100,8 @@ struct RedisConfig {
default_stream_read_count: u64,
}
-impl From<&types::RedisSettings> for RedisConfig {
- fn from(config: &types::RedisSettings) -> Self {
+impl From<&RedisSettings> for RedisConfig {
+ fn from(config: &RedisSettings) -> Self {
Self {
default_ttl: config.default_ttl,
default_stream_read_count: config.stream_read_count,
diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs
index ba4b1b8455d..76060d0219e 100644
--- a/crates/redis_interface/src/types.rs
+++ b/crates/redis_interface/src/types.rs
@@ -49,36 +49,32 @@ pub enum RedisEntryId {
impl From<RedisEntryId> for fred::types::XID {
fn from(id: RedisEntryId) -> Self {
- use fred::types::XID;
-
match id {
RedisEntryId::UserSpecifiedID {
milliseconds,
sequence_number,
- } => XID::Manual(fred::bytes_utils::format_bytes!(
+ } => Self::Manual(fred::bytes_utils::format_bytes!(
"{milliseconds}-{sequence_number}"
)),
- RedisEntryId::AutoGeneratedID => XID::Auto,
- RedisEntryId::AfterLastID => XID::Max,
- RedisEntryId::UndeliveredEntryID => XID::NewInGroup,
+ RedisEntryId::AutoGeneratedID => Self::Auto,
+ RedisEntryId::AfterLastID => Self::Max,
+ RedisEntryId::UndeliveredEntryID => Self::NewInGroup,
}
}
}
impl From<&RedisEntryId> for fred::types::XID {
fn from(id: &RedisEntryId) -> Self {
- use fred::types::XID;
-
match id {
RedisEntryId::UserSpecifiedID {
milliseconds,
sequence_number,
- } => XID::Manual(fred::bytes_utils::format_bytes!(
+ } => Self::Manual(fred::bytes_utils::format_bytes!(
"{milliseconds}-{sequence_number}"
)),
- RedisEntryId::AutoGeneratedID => XID::Auto,
- RedisEntryId::AfterLastID => XID::Max,
- RedisEntryId::UndeliveredEntryID => XID::NewInGroup,
+ RedisEntryId::AutoGeneratedID => Self::Auto,
+ RedisEntryId::AfterLastID => Self::Max,
+ RedisEntryId::UndeliveredEntryID => Self::NewInGroup,
}
}
}
diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs
index 9fcecfcdb32..94b423ebd81 100644
--- a/crates/router/src/bin/router.rs
+++ b/crates/router/src/bin/router.rs
@@ -9,11 +9,16 @@ use structopt::StructOpt;
async fn main() -> BachResult<()> {
// get commandline config before initializing config
let cmd_line = CmdLineConf::from_args();
- let conf = Settings::with_config_path(cmd_line.config_path).unwrap();
+
+ #[allow(clippy::expect_used)]
+ let conf = Settings::with_config_path(cmd_line.config_path)
+ .expect("Unable to construct application configuration");
+
let _guard = logger::setup(&conf.log)?;
logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log);
+ #[allow(clippy::expect_used)]
let (server, mut state) = router::start_server(conf)
.await
.expect("Failed to create the server");
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 7d75354244f..365d922d64e 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -15,7 +15,11 @@ async fn main() -> CustomResult<(), errors::ProcessTrackerError> {
// console_subscriber::init();
let cmd_line = CmdLineConf::from_args();
- let conf = Settings::with_config_path(cmd_line.config_path).unwrap();
+
+ #[allow(clippy::expect_used)]
+ let conf = Settings::with_config_path(cmd_line.config_path)
+ .expect("Unable to construct application configuration");
+
let mut state = routes::AppState::new(conf).await;
let _guard =
logger::setup(&state.conf.log).map_err(|_| errors::ProcessTrackerError::UnexpectedFlow)?;
@@ -57,8 +61,12 @@ async fn start_scheduler(
},
};
+ #[allow(clippy::expect_used)]
let flow = std::env::var(SCHEDULER_FLOW).expect("SCHEDULER_FLOW environment variable not set");
- let flow = scheduler::SchedulerFlow::from_str(&flow).unwrap();
+ #[allow(clippy::expect_used)]
+ let flow = scheduler::SchedulerFlow::from_str(&flow)
+ .expect("Unable to parse SchedulerFlow from environment variable");
+
let scheduler_settings = state
.conf
.scheduler
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs
index 86bc030334d..d8d4402fa8b 100644
--- a/crates/router/src/compatibility/stripe/customers/types.rs
+++ b/crates/router/src/compatibility/stripe/customers/types.rs
@@ -1,9 +1,10 @@
use std::{convert::From, default::Default};
+use common_utils::date_time;
use masking;
use serde::{Deserialize, Serialize};
-use crate::{pii, types::api};
+use crate::{logger, pii, types::api};
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CustomerAddress {
@@ -90,7 +91,18 @@ impl From<api::CustomerResponse> for CreateCustomerResponse {
Self {
id: cust.customer_id,
object: "customer".to_owned(),
- created: cust.created_at.assume_utc().unix_timestamp() as u64,
+ created: u64::try_from(cust.created_at.assume_utc().unix_timestamp()).unwrap_or_else(
+ |error| {
+ logger::error!(
+ %error,
+ "incorrect value for `customer.created_at` provided {}", cust.created_at
+ );
+ // Current timestamp converted to Unix timestamp should have a positive value
+ // for many years to come
+ u64::try_from(date_time::now().assume_utc().unix_timestamp())
+ .unwrap_or_default()
+ },
+ ),
description: cust.description,
email: cust.email,
metadata: cust.metadata,
diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs
index 9a5d921f2c5..12d0bb72b9d 100644
--- a/crates/router/src/connection.rs
+++ b/crates/router/src/connection.rs
@@ -1,4 +1,4 @@
-use async_bb8_diesel::{AsyncConnection, ConnectionError, ConnectionManager};
+use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::{CustomizeConnection, PooledConnection};
use diesel::PgConnection;
@@ -51,7 +51,9 @@ pub async fn diesel_make_pg_pool(database: &Database, test_transaction: bool) ->
}
#[allow(clippy::expect_used)]
-pub async fn pg_connection(pool: &PgPool) -> PooledConnection<ConnectionManager<PgConnection>> {
+pub async fn pg_connection(
+ pool: &PgPool,
+) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {
pool.get()
.await
.expect("Couldn't retrieve PostgreSQL connection")
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs
index e4cbec17f35..5b7569e9c69 100644
--- a/crates/router/src/connector/aci.rs
+++ b/crates/router/src/connector/aci.rs
@@ -21,7 +21,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Aci;
-impl api::ConnectorCommon for Aci {
+impl ConnectorCommon for Aci {
fn id(&self) -> &'static str {
"aci"
}
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 312231a29db..b3267138a3b 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -25,7 +25,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Adyen;
-impl api::ConnectorCommon for Adyen {
+impl ConnectorCommon for Adyen {
fn id(&self) -> &'static str {
"adyen"
}
diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs
index 3f6bfb04ad8..28ea11130d0 100644
--- a/crates/router/src/connector/applepay.rs
+++ b/crates/router/src/connector/applepay.rs
@@ -21,7 +21,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Applepay;
-impl api::ConnectorCommon for Applepay {
+impl ConnectorCommon for Applepay {
fn id(&self) -> &'static str {
"applepay"
}
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 8be464900e3..ee6c82e3ac5 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -23,7 +23,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Authorizedotnet;
-impl api::ConnectorCommon for Authorizedotnet {
+impl ConnectorCommon for Authorizedotnet {
fn id(&self) -> &'static str {
"authorizedotnet"
}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index a76a11b85cd..01a03eecdfd 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -192,18 +192,29 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest {
}
}
-#[derive(
- Debug, Clone, Default, PartialEq, Eq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
-)]
-#[repr(u8)]
-pub enum AuthorizedotnetPaymentStatus {
- Approved = 1,
- Declined = 2,
- Error = 3,
- #[default]
- HeldForReview = 4,
+// Safety: Enum as u8 conversions, we are specifying discriminants which are well within the range
+// of u8
+#[allow(clippy::as_conversions)]
+mod status {
+ #[derive(
+ Debug,
+ Clone,
+ Default,
+ PartialEq,
+ Eq,
+ serde_repr::Serialize_repr,
+ serde_repr::Deserialize_repr,
+ )]
+ #[repr(u8)]
+ pub enum AuthorizedotnetPaymentStatus {
+ Approved = 1,
+ Declined = 2,
+ Error = 3,
+ #[default]
+ HeldForReview = 4,
+ }
}
-
+pub use status::AuthorizedotnetPaymentStatus;
pub type AuthorizedotnetRefundStatus = AuthorizedotnetPaymentStatus;
impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus {
@@ -378,8 +389,8 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest {
}
}
-impl From<self::AuthorizedotnetPaymentStatus> for enums::RefundStatus {
- fn from(item: self::AuthorizedotnetRefundStatus) -> Self {
+impl From<AuthorizedotnetPaymentStatus> for enums::RefundStatus {
+ fn from(item: AuthorizedotnetRefundStatus) -> Self {
match item {
AuthorizedotnetPaymentStatus::Approved => Self::Success,
AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 28e32c6c86f..6808b9a415c 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -24,7 +24,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Braintree;
-impl api::ConnectorCommon for Braintree {
+impl ConnectorCommon for Braintree {
fn id(&self) -> &'static str {
"braintree"
}
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index 726a6c59c88..76afcdc2d06 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -26,7 +26,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Checkout;
-impl api::ConnectorCommon for Checkout {
+impl ConnectorCommon for Checkout {
fn id(&self) -> &'static str {
"checkout"
}
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 01703125aaa..e400d8b3867 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -21,7 +21,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Klarna;
-impl api::ConnectorCommon for Klarna {
+impl ConnectorCommon for Klarna {
fn id(&self) -> &'static str {
"klarna"
}
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs
index 4ba448dec70..4bb8d72d8ab 100644
--- a/crates/router/src/connector/shift4.rs
+++ b/crates/router/src/connector/shift4.rs
@@ -27,7 +27,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Shift4;
-impl<Flow, Request, Response> api::ConnectorCommonExt<Flow, Request, Response> for Shift4
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Shift4
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
@@ -50,7 +50,7 @@ where
Ok(headers)
}
}
-impl api::ConnectorCommon for Shift4 {
+impl ConnectorCommon for Shift4 {
fn id(&self) -> &'static str {
"shift4"
}
@@ -95,29 +95,20 @@ impl api::ConnectorCommon for Shift4 {
impl api::Payment for Shift4 {}
impl api::PreVerify for Shift4 {}
-impl
- services::ConnectorIntegration<
- api::Verify,
- types::VerifyRequestData,
- types::PaymentsResponseData,
- > for Shift4
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Shift4
{
}
impl api::PaymentVoid for Shift4 {}
-impl
- services::ConnectorIntegration<
- api::Void,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
- > for Shift4
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Shift4
{
}
impl api::PaymentSync for Shift4 {}
-impl
- services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for Shift4
{
fn get_headers(
@@ -190,12 +181,8 @@ impl
impl api::PaymentCapture for Shift4 {}
-impl
- services::ConnectorIntegration<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- > for Shift4
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Shift4
{
fn get_headers(
&self,
@@ -264,24 +251,16 @@ impl
impl api::PaymentSession for Shift4 {}
-impl
- services::ConnectorIntegration<
- api::Session,
- types::PaymentsSessionData,
- types::PaymentsResponseData,
- > for Shift4
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Shift4
{
//TODO: implement sessions flow
}
impl api::PaymentAuthorize for Shift4 {}
-impl
- services::ConnectorIntegration<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- > for Shift4
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Shift4
{
fn get_headers(
&self,
@@ -358,9 +337,7 @@ impl api::Refund for Shift4 {}
impl api::RefundExecute for Shift4 {}
impl api::RefundSync for Shift4 {}
-impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Shift4
-{
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Shift4 {
fn get_headers(
&self,
req: &types::RefundsRouterData<api::Execute>,
@@ -430,9 +407,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
}
}
-impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Shift4
-{
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Shift4 {
fn get_headers(
&self,
req: &types::RefundSyncRouterData,
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index dbcd99afaf6..e7d3439d38d 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -181,8 +181,8 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for Shift4RefundRequest {
}
}
-impl From<self::Shift4RefundStatus> for enums::RefundStatus {
- fn from(item: self::Shift4RefundStatus) -> Self {
+impl From<Shift4RefundStatus> for enums::RefundStatus {
+ fn from(item: Shift4RefundStatus) -> Self {
match item {
self::Shift4RefundStatus::Successful => Self::Success,
self::Shift4RefundStatus::Failed => Self::Failure,
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 2d202bab108..5df5b323d87 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -26,7 +26,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Stripe;
-impl api::ConnectorCommon for Stripe {
+impl ConnectorCommon for Stripe {
fn id(&self) -> &'static str {
"stripe"
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 204726a87ef..22f711bb910 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -528,8 +528,8 @@ pub enum RefundStatus {
RequiresAction,
}
-impl From<self::RefundStatus> for enums::RefundStatus {
- fn from(item: self::RefundStatus) -> Self {
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
match item {
self::RefundStatus::Succeeded => Self::Success,
self::RefundStatus::Failed => Self::Failure,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 9af3f0b33ca..e09e2ffd663 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -4,7 +4,7 @@ pub(crate) mod utils;
use std::fmt::Display;
-use actix_web::{body::BoxBody, http::StatusCode, HttpResponse, ResponseError};
+use actix_web::{body::BoxBody, http::StatusCode, ResponseError};
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
use config::ConfigError;
use error_stack;
@@ -24,7 +24,7 @@ pub type BachResponse<T> = BachResult<services::BachResponse<T>>;
macro_rules! impl_error_display {
($st: ident, $arg: tt) => {
- impl std::fmt::Display for $st {
+ impl Display for $st {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
fmt,
@@ -224,7 +224,7 @@ impl ResponseError for BachError {
}
}
-pub fn http_not_implemented() -> HttpResponse<BoxBody> {
+pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> {
ApiErrorResponse::NotImplemented.error_response()
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 6634ee05a63..b10478a1adc 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -21,10 +21,7 @@ use self::{
};
use super::errors::StorageErrorExt;
use crate::{
- core::{
- errors::{self, RouterResponse, RouterResult},
- payments,
- },
+ core::errors::{self, RouterResponse, RouterResult},
db::StorageInterface,
logger, pii,
routes::AppState,
@@ -62,9 +59,9 @@ where
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData>,
- FData: std::marker::Send,
+ FData: Send,
{
- let operation: BoxedOperation<F, Req> = Box::new(operation);
+ let operation: BoxedOperation<'_, F, Req> = Box::new(operation);
let (operation, validate_result) = operation
.to_validate_request()?
@@ -184,7 +181,7 @@ pub async fn payments_core<F, Res, Req, Op, FData>(
) -> RouterResponse<Res>
where
F: Send + Clone,
- FData: std::marker::Send,
+ FData: Send,
Op: Operation<F, Req> + Send + Sync + Clone,
Req: Debug,
Res: transformers::ToResponse<Req, PaymentData<F>, Op> + From<Req>,
@@ -289,7 +286,7 @@ pub async fn payments_response_for_redirection_flows<'a>(
payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
state,
merchant_account,
- payments::PaymentStatus,
+ PaymentStatus,
req,
services::api::AuthFlow::Merchant,
None,
@@ -488,7 +485,7 @@ pub fn if_not_create_change_operation<'a, Op, F>(
status: storage_enums::IntentStatus,
confirm: Option<bool>,
current: &'a Op,
-) -> BoxedOperation<F, api::PaymentsRequest>
+) -> BoxedOperation<'_, F, api::PaymentsRequest>
where
F: Send + Clone,
Op: Operation<F, api::PaymentsRequest> + Send + Sync,
@@ -515,7 +512,7 @@ where
pub fn is_confirm<'a, F: Clone + Send, R, Op>(
operation: &'a Op,
confirm: Option<bool>,
-) -> BoxedOperation<F, R>
+) -> BoxedOperation<'_, F, R>
where
PaymentConfirm: Operation<F, R>,
&'a PaymentConfirm: Operation<F, R>,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 3ddf928c048..da0286498b8 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -38,7 +38,7 @@ pub trait Feature<F, T> {
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Self>
where
- Self: std::marker::Sized,
+ Self: Sized,
F: Clone,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>;
}
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 2d9189f81b5..e36007772de 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -13,7 +13,6 @@ use crate::{
types::{
self, api,
storage::{self, enums as storage_enums},
- PaymentsAuthorizeData, PaymentsAuthorizeRouterData, PaymentsResponseData,
},
};
@@ -74,7 +73,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
}
}
-impl PaymentsAuthorizeRouterData {
+impl types::PaymentsAuthorizeRouterData {
pub async fn decide_flow<'a, 'b>(
&'b self,
state: &'a AppState,
@@ -87,9 +86,10 @@ impl PaymentsAuthorizeRouterData {
match confirm {
Some(true) => {
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::Authorize,
- PaymentsAuthorizeData,
- PaymentsResponseData,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index ad7458e94af..e54f5a970b9 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -11,7 +11,6 @@ use crate::{
types::{
self, api,
storage::{self, enums},
- PaymentsCancelRouterData, PaymentsResponseData,
},
};
@@ -24,7 +23,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
state: &AppState,
connector_id: &str,
merchant_account: &storage::MerchantAccount,
- ) -> RouterResult<PaymentsCancelRouterData> {
+ ) -> RouterResult<types::PaymentsCancelRouterData> {
transformers::construct_payment_router_data::<api::Void, types::PaymentsCancelData>(
state,
self.clone(),
@@ -58,7 +57,7 @@ impl Feature<api::Void, types::PaymentsCancelData>
}
}
-impl PaymentsCancelRouterData {
+impl types::PaymentsCancelRouterData {
#[allow(clippy::too_many_arguments)]
pub async fn decide_flow<'a, 'b>(
&'b self,
@@ -69,9 +68,10 @@ impl PaymentsCancelRouterData {
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::Void,
types::PaymentsCancelData,
- PaymentsResponseData,
+ types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index 469308e8880..1fc736bcccb 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -11,7 +11,6 @@ use crate::{
types::{
self, api,
storage::{self, enums},
- PaymentsCaptureData, PaymentsCaptureRouterData, PaymentsResponseData,
},
};
@@ -25,7 +24,7 @@ impl
state: &AppState,
connector_id: &str,
merchant_account: &storage::MerchantAccount,
- ) -> RouterResult<PaymentsCaptureRouterData> {
+ ) -> RouterResult<types::PaymentsCaptureRouterData> {
transformers::construct_payment_router_data::<api::Capture, types::PaymentsCaptureData>(
state,
self.clone(),
@@ -59,7 +58,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
}
}
-impl PaymentsCaptureRouterData {
+impl types::PaymentsCaptureRouterData {
#[allow(clippy::too_many_arguments)]
pub async fn decide_flow<'a, 'b>(
&'b self,
@@ -70,9 +69,10 @@ impl PaymentsCaptureRouterData {
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::Capture,
- PaymentsCaptureData,
- PaymentsResponseData,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index e8240e5326e..1e471b593b1 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -11,7 +11,6 @@ use crate::{
types::{
self, api,
storage::{self, enums},
- PaymentsResponseData, PaymentsSyncData, PaymentsSyncRouterData,
},
};
@@ -60,7 +59,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>
}
}
-impl PaymentsSyncRouterData {
+impl types::PaymentsSyncRouterData {
pub async fn decide_flow<'a, 'b>(
&'b self,
state: &'a AppState,
@@ -70,9 +69,10 @@ impl PaymentsSyncRouterData {
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::PSync,
- PaymentsSyncData,
- PaymentsResponseData,
+ types::PaymentsSyncData,
+ types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 52fea4646bf..e76eb518a3c 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -110,6 +110,7 @@ impl types::PaymentsSessionRouterData {
api::GetToken::Metadata => create_gpay_session_token(self),
api::GetToken::Connector => {
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::Session,
types::PaymentsSessionData,
types::PaymentsResponseData,
diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs
index e16caf0a4a2..ef019350d47 100644
--- a/crates/router/src/core/payments/flows/verfiy_flow.rs
+++ b/crates/router/src/core/payments/flows/verfiy_flow.rs
@@ -70,6 +70,7 @@ impl types::VerifyRouterData {
match confirm {
Some(true) => {
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::Verify,
types::VerifyRequestData,
types::PaymentsResponseData,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 1967fe41dc6..b0e8b6c1e13 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -566,7 +566,7 @@ pub(crate) async fn call_payment_method(
pub(crate) fn client_secret_auth<P>(
payload: P,
- auth_type: &services::api::MerchantAuthentication,
+ auth_type: &services::api::MerchantAuthentication<'_>,
) -> RouterResult<P>
where
P: services::Authenticate,
@@ -1195,7 +1195,7 @@ pub fn make_url_with_signature(
}
pub fn hmac_sha256_sorted_query_params<'a>(
- params: &mut [(Cow<str>, Cow<str>)],
+ params: &mut [(Cow<'_, str>, Cow<'_, str>)],
key: &'a str,
) -> RouterResult<String> {
params.sort();
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 2b6d4fa2be0..fbd9e0d6ca6 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -8,21 +8,18 @@ mod payment_session;
mod payment_start;
mod payment_status;
mod payment_update;
+
use async_trait::async_trait;
use error_stack::{report, ResultExt};
-pub use payment_cancel::PaymentCancel;
-pub use payment_capture::PaymentCapture;
-pub use payment_confirm::PaymentConfirm;
-pub use payment_create::PaymentCreate;
-pub use payment_method_validate::PaymentMethodValidate;
-pub use payment_response::PaymentResponse;
-pub use payment_session::PaymentSession;
-pub use payment_start::PaymentStart;
-pub use payment_status::PaymentStatus;
-pub use payment_update::PaymentUpdate;
use router_env::{instrument, tracing};
-use storage::Customer;
+pub use self::{
+ payment_cancel::PaymentCancel, payment_capture::PaymentCapture,
+ payment_confirm::PaymentConfirm, payment_create::PaymentCreate,
+ payment_method_validate::PaymentMethodValidate, payment_response::PaymentResponse,
+ payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus,
+ payment_update::PaymentUpdate,
+};
use super::{helpers, CustomerDetails, PaymentData};
use crate::{
core::errors::{self, CustomResult, RouterResult},
@@ -150,7 +147,7 @@ pub trait UpdateTracker<F, D, Req>: Send {
db: &dyn StorageInterface,
payment_id: &api::PaymentIdType,
payment_data: D,
- customer: Option<Customer>,
+ customer: Option<storage::Customer>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, Req>, D)>
where
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 0c74ef8718f..81620fb9e77 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -13,7 +13,7 @@ use crate::{
db::StorageInterface,
routes::AppState,
types::{
- api::{self, PaymentIdTypeExt, PaymentsCaptureRequest},
+ api::{self, PaymentIdTypeExt},
storage::{self, enums},
transformers::ForeignInto,
},
@@ -34,7 +34,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
state: &'a AppState,
payment_id: &api::PaymentIdType,
merchant_id: &str,
- request: &PaymentsCaptureRequest,
+ request: &api::PaymentsCaptureRequest,
_mandate_type: Option<api::MandateTxnType>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 239bfabef08..185889feaa0 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -101,7 +101,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
- let db = db as &dyn StorageInterface;
let connector_response = db
.find_connector_response_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index b3c12ff2bfb..cf847caae47 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -16,7 +16,7 @@ use crate::{
routes::AppState,
types::{
api::{self, enums as api_enums, PaymentIdTypeExt},
- storage::{self, enums, Customer},
+ storage::{self, enums},
transformers::ForeignInto,
},
utils::OptionExt,
@@ -158,7 +158,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P
_db: &dyn StorageInterface,
_payment_id: &api::PaymentIdType,
payment_data: PaymentData<F>,
- _customer: Option<Customer>,
+ _customer: Option<storage::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsStartRequest>,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index d0682df3c82..693a1f4ed8f 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -109,7 +109,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
&'a self,
state: &'a AppState,
payment_attempt: &storage::PaymentAttempt,
- ) -> CustomResult<(), errors::ApiErrorResponse> {
+ ) -> CustomResult<(), ApiErrorResponse> {
helpers::add_domain_task_to_pt(self, state, payment_attempt).await
}
@@ -118,7 +118,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
merchant_account: &storage::MerchantAccount,
state: &AppState,
request_connector: Option<api_enums::Connector>,
- ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
+ ) -> CustomResult<api::ConnectorCallType, ApiErrorResponse> {
helpers::get_connector_default(merchant_account, state, request_connector).await
}
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 129ba54fe9c..a9d1560b81d 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -112,7 +112,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
- let db = db as &dyn StorageInterface;
let connector_response = db
.find_connector_response_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index eea134d4537..7e963424505 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -13,8 +13,7 @@ use crate::{
routes::AppState,
services::{self, RedirectForm},
types::{
- self,
- api::{self, NextAction, PaymentsResponse},
+ self, api,
storage::{self, enums},
transformers::ForeignInto,
},
@@ -32,8 +31,7 @@ where
T: TryFrom<PaymentData<F>>,
types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>,
F: Clone,
- error_stack::Report<errors::ApiErrorResponse>:
- std::convert::From<<T as TryFrom<PaymentData<F>>>::Error>,
+ error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentData<F>>>::Error>,
{
//TODO: everytime parsing the json may have impact?
@@ -260,10 +258,10 @@ where
.map_err(|_| errors::ApiErrorResponse::InternalServerError)?;
services::BachResponse::Form(form)
} else {
- let mut response: PaymentsResponse = request.into();
+ let mut response: api::PaymentsResponse = request.into();
let mut next_action_response = None;
if payment_intent.status == enums::IntentStatus::RequiresCustomerAction {
- next_action_response = Some(NextAction {
+ next_action_response = Some(api::NextAction {
next_action_type: api::NextActionType::RedirectToUrl,
redirect_to_url: Some(helpers::create_startpay_url(
server,
@@ -342,7 +340,7 @@ where
)
}
}
- None => services::BachResponse::Json(PaymentsResponse {
+ None => services::BachResponse::Json(api::PaymentsResponse {
payment_id: Some(payment_attempt.payment_id),
merchant_id: Some(payment_attempt.merchant_id),
status: payment_intent.status.foreign_into(),
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 9e7fcf55fd2..8c5bd3669fb 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -127,6 +127,7 @@ pub async fn trigger_refund_to_gateway(
logger::debug!(?router_data);
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::Execute,
types::RefundsData,
types::RefundsResponseData,
@@ -268,6 +269,7 @@ pub async fn sync_refund_with_gateway(
.await?;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
api::RSync,
types::RefundsData,
types::RefundsResponseData,
diff --git a/crates/router/src/cors.rs b/crates/router/src/cors.rs
index 5235d6b78f7..07e12b0d3fd 100644
--- a/crates/router/src/cors.rs
+++ b/crates/router/src/cors.rs
@@ -1,8 +1,7 @@
-use actix_cors::Cors;
// use actix_web::http::header;
pub fn cors() -> actix_cors::Cors {
- Cors::permissive() // Warn : Never use in production
+ actix_cors::Cors::permissive() // FIXME : Never use in production
/*
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
diff --git a/crates/router/src/db/connector_response.rs b/crates/router/src/db/connector_response.rs
index 6fe5d282054..b35e55b291b 100644
--- a/crates/router/src/db/connector_response.rs
+++ b/crates/router/src/db/connector_response.rs
@@ -88,6 +88,7 @@ impl ConnectorResponseInterface for MockDb {
) -> CustomResult<storage::ConnectorResponse, errors::StorageError> {
let mut connector_response = self.connector_response.lock().await;
let response = storage::ConnectorResponse {
+ #[allow(clippy::as_conversions)]
id: connector_response.len() as i32,
payment_id: new.payment_id,
merchant_id: new.merchant_id,
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index accfc96859a..234ded5b2d2 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -153,6 +153,7 @@ impl CustomerInterface for MockDb {
) -> CustomResult<storage::Customer, errors::StorageError> {
let mut customers = self.customers.lock().await;
let customer = storage::Customer {
+ #[allow(clippy::as_conversions)]
id: customers.len() as i32,
customer_id: customer_data.customer_id,
merchant_id: customer_data.merchant_id,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 750d8af5b93..d0e48d114e5 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -122,6 +122,7 @@ impl MerchantAccountInterface for MockDb {
) -> CustomResult<storage::MerchantAccount, errors::StorageError> {
let mut accounts = self.merchant_accounts.lock().await;
let account = storage::MerchantAccount {
+ #[allow(clippy::as_conversions)]
id: accounts.len() as i32,
merchant_id: merchant_account.merchant_id,
api_key: merchant_account.api_key,
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index d4220606323..347506c15d6 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -163,6 +163,7 @@ impl MerchantConnectorAccountInterface for MockDb {
) -> CustomResult<storage::MerchantConnectorAccount, errors::StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
let account = storage::MerchantConnectorAccount {
+ #[allow(clippy::as_conversions)]
id: accounts.len() as i32,
merchant_id: t.merchant_id.unwrap_or_default(),
connector_name: t.connector_name.unwrap_or_default(),
diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs
index 52ae9ca32de..de6abb99ec2 100644
--- a/crates/router/src/db/payment_attempt.rs
+++ b/crates/router/src/db/payment_attempt.rs
@@ -207,6 +207,7 @@ impl PaymentAttemptInterface for MockDb {
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<types::PaymentAttempt, errors::StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
+ #[allow(clippy::as_conversions)]
let id = payment_attempts.len() as i32;
let time = common_utils::date_time::now();
diff --git a/crates/router/src/db/payment_intent.rs b/crates/router/src/db/payment_intent.rs
index df170182a4f..0149c24365c 100644
--- a/crates/router/src/db/payment_intent.rs
+++ b/crates/router/src/db/payment_intent.rs
@@ -343,6 +343,7 @@ impl PaymentIntentInterface for MockDb {
let mut payment_intents = self.payment_intents.lock().await;
let time = common_utils::date_time::now();
let payment_intent = types::PaymentIntent {
+ #[allow(clippy::as_conversions)]
id: payment_intents.len() as i32,
payment_id: new.payment_id,
merchant_id: new.merchant_id,
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index abeaaff7712..2cbb8cec7af 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -1,9 +1,8 @@
-use error_stack::Report;
use storage_models::errors::DatabaseError;
use super::MockDb;
use crate::{
- core::errors::{self, CustomResult, StorageError},
+ core::errors::{self, CustomResult},
types::storage::{self as storage_types, enums},
};
@@ -571,6 +570,7 @@ impl RefundInterface for MockDb {
let current_time = common_utils::date_time::now();
let refund = storage_types::Refund {
+ #[allow(clippy::as_conversions)]
id: refunds.len() as i32,
internal_reference_id: new.internal_reference_id,
refund_id: new.refund_id,
@@ -638,9 +638,7 @@ impl RefundInterface for MockDb {
.find(|refund| refund.merchant_id == merchant_id && refund.refund_id == refund_id)
.cloned()
.ok_or_else(|| {
- Report::from(StorageError::DatabaseError(Report::from(
- DatabaseError::NotFound,
- )))
+ errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into()
})
}
diff --git a/crates/router/src/db/temp_card.rs b/crates/router/src/db/temp_card.rs
index 0b3af9cce40..15b998d2836 100644
--- a/crates/router/src/db/temp_card.rs
+++ b/crates/router/src/db/temp_card.rs
@@ -87,6 +87,7 @@ impl TempCardInterface for MockDb {
) -> CustomResult<storage::TempCard, errors::StorageError> {
let mut cards = self.temp_cards.lock().await;
let card = storage::TempCard {
+ #[allow(clippy::as_conversions)]
id: cards.len() as i32,
date_created: insert.date_created,
txn_id: insert.txn_id,
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 5d1d8cde95a..84252c835b5 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -1,24 +1,4 @@
#![forbid(unsafe_code)]
-// FIXME: I strongly advise to add this worning.
-// #![warn(missing_docs)]
-
-// FIXME: I recommend to add these wornings too, although there is no harm if these wanrings will stay disabled.
-// #![warn(rust_2018_idioms)]
-// #![warn(missing_debug_implementations)]
-#![warn(
- // clippy::as_conversions,
- clippy::expect_used,
- // clippy::integer_arithmetic,
- clippy::missing_panics_doc,
- clippy::panic,
- clippy::panic_in_result_fn,
- clippy::panicking_unwrap,
- clippy::todo,
- clippy::unreachable,
- clippy::unwrap_in_result,
- clippy::unwrap_used,
- clippy::use_self
-)]
#![recursion_limit = "256"]
#[cfg(feature = "stripe")]
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 868dc2fe754..dc726c654ce 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -166,7 +166,7 @@ mod tests {
#[test]
fn test_custom_list_deserialization() {
let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true&accepted_countries=US&accepted_countries=IN";
- let de_query: web::Query<payment_methods::ListPaymentMethodRequest> =
+ let de_query: web::Query<ListPaymentMethodRequest> =
web::Query::from_query(dummy_data).unwrap();
let de_struct = de_query.into_inner();
assert_eq!(
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index bbc26431c08..97ba2c8fcaa 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -5,11 +5,7 @@ use router_env::{
};
use super::app::AppState;
-use crate::{
- core::refunds::*,
- services::api,
- types::api::refunds::{self, RefundRequest},
-};
+use crate::{core::refunds::*, services::api, types::api::refunds};
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))]
// #[post("")]
@@ -54,7 +50,7 @@ pub async fn refunds_retrieve(
pub async fn refunds_update(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<RefundRequest>,
+ json_payload: web::Json<refunds::RefundRequest>,
path: web::Path<String>,
) -> HttpResponse {
let refund_id = path.into_inner();
diff --git a/crates/router/src/scheduler/producer.rs b/crates/router/src/scheduler/producer.rs
index a190cf9104e..791691c0bbf 100644
--- a/crates/router/src/scheduler/producer.rs
+++ b/crates/router/src/scheduler/producer.rs
@@ -147,6 +147,9 @@ pub async fn fetch_producer_tasks(
}
new_tasks.append(&mut pending_tasks);
+
+ // Safety: Assuming we won't deal with more than `u64::MAX` tasks at once
+ #[allow(clippy::as_conversions)]
metrics::TASKS_PICKED_COUNT.add(&metrics::CONTEXT, new_tasks.len() as u64, &[]);
Ok(new_tasks)
}
diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs
index e43f65ed4ba..d8f409f94cf 100644
--- a/crates/router/src/scheduler/utils.rs
+++ b/crates/router/src/scheduler/utils.rs
@@ -26,6 +26,8 @@ pub async fn divide_and_append_tasks(
settings: &SchedulerSettings,
) -> CustomResult<(), errors::ProcessTrackerError> {
let batches = divide(tasks, settings);
+ // Safety: Assuming we won't deal with more than `u64::MAX` batches at once
+ #[allow(clippy::as_conversions)]
metrics::BATCHES_CREATED.add(&metrics::CONTEXT, batches.len() as u64, &[]); // Metrics
for batch in batches {
let result = update_status_and_append(state, flow, batch).await;
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 96a5c559082..52f1af53852 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -22,12 +22,12 @@ use crate::{
payments,
},
db::StorageInterface,
- logger, routes,
+ logger,
routes::AppState,
types::{
self, api,
storage::{self, enums},
- ErrorResponse, Response,
+ ErrorResponse,
},
utils::{self, OptionExt},
};
@@ -36,7 +36,7 @@ pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
- fn get_connector_integration(&self) -> BoxedConnectorIntegration<T, Req, Resp>;
+ fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
}
impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
@@ -86,7 +86,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re
fn handle_response(
&self,
data: &types::RouterData<T, Req, Resp>,
- _res: Response,
+ _res: types::Response,
) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone,
@@ -185,7 +185,7 @@ where
pub(crate) async fn call_connector_api(
state: &AppState,
request: Request,
-) -> CustomResult<Result<Response, Response>, errors::ApiClientError> {
+) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
let current_time = Instant::now();
let response = send_request(state, request).await;
@@ -256,7 +256,7 @@ async fn send_request(
#[instrument(skip_all)]
async fn handle_response(
response: CustomResult<reqwest::Response, errors::ApiClientError>,
-) -> CustomResult<Result<Response, Response>, errors::ApiClientError> {
+) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
response
.map(|response| async {
logger::info!(?response);
@@ -272,7 +272,7 @@ async fn handle_response(
.into_report()
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Error while waiting for response")?;
- Ok(Ok(Response {
+ Ok(Ok(types::Response {
response,
status_code,
}))
@@ -308,7 +308,7 @@ async fn handle_response(
};
Err(report!(error).attach_printable("Client error response received"))
*/
- Ok(Err(Response {
+ Ok(Err(types::Response {
response: bytes,
status_code,
}))
@@ -408,14 +408,14 @@ pub enum AuthFlow {
Merchant,
}
-pub(crate) fn get_auth_flow(auth_type: &MerchantAuthentication) -> AuthFlow {
+pub(crate) fn get_auth_flow(auth_type: &MerchantAuthentication<'_>) -> AuthFlow {
match auth_type {
MerchantAuthentication::ApiKey => AuthFlow::Merchant,
_ => AuthFlow::Client,
}
}
-pub(crate) fn get_auth_type(request: &HttpRequest) -> RouterResult<MerchantAuthentication> {
+pub(crate) fn get_auth_type(request: &HttpRequest) -> RouterResult<MerchantAuthentication<'_>> {
let api_key = get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?;
if api_key.starts_with("pk_") {
Ok(MerchantAuthentication::PublishableKey)
@@ -426,17 +426,17 @@ pub(crate) fn get_auth_type(request: &HttpRequest) -> RouterResult<MerchantAuthe
#[instrument(skip(request, payload, state, func))]
pub(crate) async fn server_wrap_util<'a, 'b, T, Q, F, Fut>(
- state: &'b routes::AppState,
+ state: &'b AppState,
request: &'a HttpRequest,
payload: T,
func: F,
api_authentication: ApiAuthentication<'a>,
) -> RouterResult<BachResponse<Q>>
where
- F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut,
+ F: Fn(&'b AppState, storage::MerchantAccount, T) -> Fut,
Fut: Future<Output = RouterResponse<Q>>,
Q: Serialize + Debug + 'a,
- T: std::fmt::Debug,
+ T: Debug,
{
let merchant_account = match api_authentication {
ApiAuthentication::Merchant(merchant_auth) => {
@@ -455,7 +455,7 @@ where
fields(request_method, request_url_path)
)]
pub(crate) async fn server_wrap<'a, 'b, A, T, Q, F, Fut>(
- state: &'b routes::AppState,
+ state: &'b AppState,
request: &'a HttpRequest,
payload: T,
func: F,
@@ -463,10 +463,10 @@ pub(crate) async fn server_wrap<'a, 'b, A, T, Q, F, Fut>(
) -> HttpResponse
where
A: Into<ApiAuthentication<'a>> + Debug,
- F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut,
+ F: Fn(&'b AppState, storage::MerchantAccount, T) -> Fut,
Fut: Future<Output = RouterResult<BachResponse<Q>>>,
Q: Serialize + Debug + 'a,
- T: std::fmt::Debug,
+ T: Debug,
{
let api_authentication = api_authentication.into();
let request_method = request.method().as_str();
@@ -594,9 +594,9 @@ pub async fn authenticate_connector<'a>(
}
pub(crate) fn get_auth_type_and_check_client_secret<P>(
- req: &actix_web::HttpRequest,
+ req: &HttpRequest,
payload: P,
-) -> RouterResult<(P, MerchantAuthentication)>
+) -> RouterResult<(P, MerchantAuthentication<'_>)>
where
P: Authenticate,
{
@@ -608,7 +608,7 @@ where
}
pub(crate) async fn authenticate_eph_key<'a>(
- req: &'a actix_web::HttpRequest,
+ req: &'a HttpRequest,
store: &dyn StorageInterface,
customer_id: String,
) -> RouterResult<MerchantAuthentication<'a>> {
@@ -748,7 +748,7 @@ pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup {
}
}
- (maud::PreEscaped(r#"<script type="text/javascript"> var frm = document.getElementById("payment_form"); window.setTimeout(function () { frm.submit(); }, 500); </script>"#))
+ (PreEscaped(r#"<script type="text/javascript"> var frm = document.getElementById("payment_form"); window.setTimeout(function () { frm.submit(); }, 500); </script>"#))
}
}
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index d390388b35a..ff73559ad9f 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -7,7 +7,7 @@ pub mod payments;
pub mod refunds;
pub mod webhooks;
-use std::{fmt::Debug, marker, str::FromStr};
+use std::{fmt::Debug, str::FromStr};
use bytes::Bytes;
use error_stack::{report, IntoReport, ResultExt};
@@ -88,7 +88,7 @@ impl<T: Refund + Payment + Debug + ConnectorRedirectResponse + Send + IncomingWe
{
}
-type BoxedConnector = Box<&'static (dyn Connector + marker::Sync)>;
+type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
// Normal flow will call the connector and follow the flow specific operations (capture, authorize)
// SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk )
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index cc43782f9f2..fb068b8a048 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -81,8 +81,8 @@ pub(crate) trait CreatePaymentMethodExt {
the_subtype: Option<U>,
) -> bool
where
- T: std::cmp::Eq + std::hash::Hash,
- U: std::cmp::PartialEq;
+ T: Eq + std::hash::Hash,
+ U: PartialEq;
}
impl CreatePaymentMethodExt for CreatePaymentMethod {
@@ -122,8 +122,8 @@ impl CreatePaymentMethodExt for CreatePaymentMethod {
the_subtype: Option<U>,
) -> bool
where
- T: std::cmp::Eq + std::hash::Hash,
- U: std::cmp::PartialEq,
+ T: Eq + std::hash::Hash,
+ U: PartialEq,
{
let the_subtype = match the_subtype {
Some(st) => st,
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 97975d6acab..661746e819b 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -1,4 +1,3 @@
-use api_models::payments;
pub use api_models::payments::{
AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, CCard,
CustomerAcceptance, MandateData, MandateTxnType, MandateType, MandateValidationFields,
@@ -115,7 +114,7 @@ impl MandateValidationFieldsExt for MandateValidationFields {
impl From<Foreign<storage::PaymentIntent>> for Foreign<PaymentsResponse> {
fn from(item: Foreign<storage::PaymentIntent>) -> Self {
let item = item.0;
- payments::PaymentsResponse {
+ PaymentsResponse {
payment_id: Some(item.payment_id),
merchant_id: Some(item.merchant_id),
status: item.status.foreign_into(),
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 9a63a821aef..526f1afbf30 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -47,7 +47,7 @@ pub mod error_parser {
}
impl ResponseError for CustomJsonError {
- fn status_code(&self) -> reqwest::StatusCode {
+ fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
diff --git a/crates/router/src/utils/storage_partitioning.rs b/crates/router/src/utils/storage_partitioning.rs
index 7136b6d7cb9..943b84d1895 100644
--- a/crates/router/src/utils/storage_partitioning.rs
+++ b/crates/router/src/utils/storage_partitioning.rs
@@ -1,9 +1,9 @@
pub(crate) trait KvStorePartition {
- fn partition_number(key: PartitionKey, num_partitions: u8) -> u32 {
+ fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 {
crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions)
}
- fn shard_key(key: PartitionKey, num_partitions: u8) -> String {
+ fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String {
format!("shard_{}", Self::partition_number(key, num_partitions))
}
}
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index a8d8f858660..630107deabe 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -108,6 +108,7 @@ async fn payments_create_success() {
get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -140,6 +141,7 @@ async fn payments_create_failure() {
get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -178,6 +180,7 @@ async fn refund_for_successful_payments() {
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -196,6 +199,7 @@ async fn refund_for_successful_payments() {
"The payment failed"
);
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Execute,
types::RefundsData,
types::RefundsResponseData,
@@ -234,6 +238,7 @@ async fn refunds_create_failure() {
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Execute,
types::RefundsData,
types::RefundsResponseData,
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index 31feab732ff..6b9fe6b67cc 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -106,6 +106,7 @@ async fn payments_create_success() {
get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -142,6 +143,7 @@ async fn payments_create_failure() {
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -186,6 +188,7 @@ async fn refunds_create_success() {
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Execute,
types::RefundsData,
types::RefundsResponseData,
@@ -222,6 +225,7 @@ async fn refunds_create_failure() {
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Execute,
types::RefundsData,
types::RefundsResponseData,
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index 0bea948fa96..cefd2e1d8a8 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -105,6 +105,7 @@ async fn test_checkout_payment_success() {
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -143,6 +144,7 @@ async fn test_checkout_refund_success() {
get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -166,6 +168,7 @@ async fn test_checkout_refund_success() {
);
// Successful refund
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Execute,
types::RefundsData,
types::RefundsResponseData,
@@ -209,6 +212,7 @@ async fn test_checkout_payment_failure() {
get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -241,6 +245,7 @@ async fn test_checkout_refund_failure() {
get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
@@ -262,6 +267,7 @@ async fn test_checkout_refund_failure() {
);
// Unsuccessful refund
let connector_integration: services::BoxedConnectorIntegration<
+ '_,
types::api::Execute,
types::RefundsData,
types::RefundsResponseData,
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index e06897d9ab1..5be73e5aaaa 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -11,6 +11,7 @@ pub(crate) struct ConnectorAuthentication {
impl ConnectorAuthentication {
pub(crate) fn new() -> Self {
+ #[allow(clippy::expect_used)]
toml::de::from_slice(
&std::fs::read("tests/connectors/auth.toml")
.expect("connector authentication config file not found"),
@@ -26,7 +27,7 @@ pub(crate) struct HeaderKey {
impl From<HeaderKey> for ConnectorAuthType {
fn from(key: HeaderKey) -> Self {
- ConnectorAuthType::HeaderKey {
+ Self::HeaderKey {
api_key: key.api_key,
}
}
@@ -40,7 +41,7 @@ pub(crate) struct BodyKey {
impl From<BodyKey> for ConnectorAuthType {
fn from(key: BodyKey) -> Self {
- ConnectorAuthType::BodyKey {
+ Self::BodyKey {
api_key: key.api_key,
key1: key.key1,
}
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 93c55c6e580..b4ea15522d8 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
+
mod aci;
mod authorizedotnet;
mod checkout;
diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs
index dd4f68f4e72..d7d559555c4 100644
--- a/crates/router/tests/connectors/shift4.rs
+++ b/crates/router/tests/connectors/shift4.rs
@@ -8,7 +8,7 @@ use crate::{
};
struct Shift4;
-impl utils::ConnectorActions for Shift4 {}
+impl ConnectorActions for Shift4 {}
impl utils::Connector for Shift4 {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Shift4;
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 569a38586d2..51fdfc87109 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -5,14 +5,8 @@ use masking::Secret;
use router::{
core::payments,
db::StorageImpl,
- routes,
- services::{self},
- types::{
- self,
- api::{self},
- storage::enums,
- PaymentAddress, RouterData,
- },
+ routes, services,
+ types::{self, api, storage::enums, PaymentAddress},
};
pub trait Connector {
@@ -93,7 +87,7 @@ async fn call_connector<
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
- request: RouterData<T, Req, Resp>,
+ request: types::RouterData<T, Req, Resp>,
integration: services::BoxedConnectorIntegration<'_, T, Req, Resp>,
) -> types::RouterData<T, Req, Resp> {
use router::configs::settings::Settings;
@@ -115,7 +109,7 @@ pub struct CCardType(pub api::CCard);
impl Default for CCardType {
fn default() -> Self {
- CCardType(api::CCard {
+ Self(api::CCard {
card_number: Secret::new("4200000000000000".to_string()),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
@@ -141,7 +135,7 @@ impl Default for PaymentAuthorizeType {
browser_info: None,
order_details: None,
};
- PaymentAuthorizeType(data)
+ Self(data)
}
}
@@ -155,7 +149,7 @@ impl Default for PaymentRefundType {
connector_transaction_id: String::new(),
refund_amount: 100,
};
- PaymentRefundType(data)
+ Self(data)
}
}
diff --git a/crates/router/tests/customers.rs b/crates/router/tests/customers.rs
index ce7f6b5f792..f765b9f4619 100644
--- a/crates/router/tests/customers.rs
+++ b/crates/router/tests/customers.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::unwrap_used)]
+
mod utils;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
diff --git a/crates/router/tests/integration_demo.rs b/crates/router/tests/integration_demo.rs
index d838f8e798f..1fc675ffa9a 100644
--- a/crates/router/tests/integration_demo.rs
+++ b/crates/router/tests/integration_demo.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::unwrap_used)]
+
mod utils;
#[allow(dead_code)]
diff --git a/crates/router/tests/payouts.rs b/crates/router/tests/payouts.rs
index ff36fa13cf2..0c208340ace 100644
--- a/crates/router/tests/payouts.rs
+++ b/crates/router/tests/payouts.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::unwrap_used)]
+
mod utils;
#[actix_web::test]
diff --git a/crates/router/tests/refunds.rs b/crates/router/tests/refunds.rs
index 7eff4f2e9b0..608b16f5cad 100644
--- a/crates/router/tests/refunds.rs
+++ b/crates/router/tests/refunds.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::unwrap_used)]
+
use utils::{mk_service, AppClient};
mod utils;
diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs
index 964ae87668f..6063680cb65 100644
--- a/crates/router/tests/utils.rs
+++ b/crates/router/tests/utils.rs
@@ -1,4 +1,10 @@
-#![allow(dead_code)]
+#![allow(
+ dead_code,
+ clippy::expect_used,
+ clippy::missing_panics_doc,
+ clippy::unwrap_used
+)]
+
use actix_http::{body::MessageBody, Request};
use actix_web::{
dev::{Service, ServiceResponse},
@@ -31,11 +37,8 @@ async fn stripemock() -> Option<String> {
None
}
-pub async fn mk_service() -> impl actix_web::dev::Service<
- actix_http::Request,
- Response = actix_web::dev::ServiceResponse<impl actix_web::body::MessageBody>,
- Error = actix_web::Error,
-> {
+pub async fn mk_service(
+) -> impl Service<Request, Response = ServiceResponse<impl MessageBody>, Error = actix_web::Error> {
let mut conf = Settings::new().unwrap();
let request_body_limit = conf.server.request_body_limit;
@@ -63,8 +66,8 @@ pub struct AppClient<T> {
}
impl AppClient<Guest> {
- pub fn guest() -> AppClient<Guest> {
- AppClient { state: Guest }
+ pub fn guest() -> Self {
+ Self { state: Guest }
}
}
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs
index cba0ef30129..8f9015d484c 100644
--- a/crates/router_derive/src/lib.rs
+++ b/crates/router_derive/src/lib.rs
@@ -133,6 +133,11 @@ pub fn diesel_enum(
/// ```
///
+/// # Panics
+///
+/// Panics if a struct without named fields is provided as input to the macro
+// FIXME: Remove allowed warnings, raise compile errors in a better manner instead of panicking
+#[allow(clippy::panic, clippy::unwrap_used)]
#[proc_macro_derive(Setter, attributes(auth_based))]
pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
@@ -145,6 +150,7 @@ pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
{
named
} else {
+ // FIXME: Use `compile_error!()` instead
panic!("You can't use this proc-macro on structs without fields");
};
diff --git a/crates/router_derive/src/macros/api_error.rs b/crates/router_derive/src/macros/api_error.rs
index 56d59317cf4..8c6790a76df 100644
--- a/crates/router_derive/src/macros/api_error.rs
+++ b/crates/router_derive/src/macros/api_error.rs
@@ -74,11 +74,15 @@ fn implement_error_type(
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(..) => quote! { {..} },
};
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_type = properties.error_type.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => #error_type });
}
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_type_enum = type_properties.error_type_enum.as_ref().unwrap();
quote! {
pub fn error_type(&self) -> #error_type_enum {
@@ -101,6 +105,8 @@ fn implement_error_code(
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(..) => quote! { {..} },
};
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_code = properties.code.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => #error_code.to_string() });
@@ -129,11 +135,17 @@ fn implement_error_message(
let fields = fields
.named
.iter()
- .map(|f| f.ident.as_ref().unwrap())
+ .map(|f| {
+ // Safety: Named fields are guaranteed to have an identifier.
+ #[allow(clippy::unwrap_used)]
+ f.ident.as_ref().unwrap()
+ })
.collect::<Punctuated<&Ident, Comma>>();
quote! { {#fields} }
}
};
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_message = properties.message.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => format!(#error_message) });
@@ -150,7 +162,7 @@ fn implement_error_message(
fn implement_serialize(
enum_name: &Ident,
- generics: (&ImplGenerics, &TypeGenerics, Option<&WhereClause>),
+ generics: (&ImplGenerics<'_>, &TypeGenerics<'_>, Option<&WhereClause>),
type_properties: &ErrorTypeProperties,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
@@ -165,14 +177,22 @@ fn implement_serialize(
let fields = fields
.named
.iter()
- .map(|f| f.ident.as_ref().unwrap())
+ .map(|f| {
+ // Safety: Named fields are guaranteed to have an identifier.
+ #[allow(clippy::unwrap_used)]
+ f.ident.as_ref().unwrap()
+ })
.collect::<Punctuated<&Ident, Comma>>();
quote! { {#fields} }
}
};
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_message = properties.message.as_ref().unwrap();
- let msg_unused_fields = get_unused_fields(&variant.fields, &error_message.value()).unwrap();
+ let msg_unused_fields = get_unused_fields(&variant.fields, &error_message.value());
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_type_enum = type_properties.error_type_enum.as_ref().unwrap();
let response_definition = if msg_unused_fields.is_empty() {
quote! {
@@ -188,6 +208,8 @@ fn implement_serialize(
let mut extra_fields = Vec::new();
for field in &msg_unused_fields {
let vis = &field.vis;
+ // Safety: `msq_unused_fields` is expected to contain named fields only.
+ #[allow(clippy::unwrap_used)]
let ident = &field.ident.as_ref().unwrap();
let ty = &field.ty;
extra_fields.push(quote! { #vis #ident: #ty });
@@ -204,12 +226,20 @@ fn implement_serialize(
}
};
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let error_type = properties.error_type.as_ref().unwrap();
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let code = properties.code.as_ref().unwrap();
+ // Safety: Missing attributes are already checked before this function is called.
+ #[allow(clippy::unwrap_used)]
let message = properties.message.as_ref().unwrap();
let extra_fields = msg_unused_fields
.iter()
.map(|field| {
+ // Safety: `extra_fields` is expected to contain named fields only.
+ #[allow(clippy::unwrap_used)]
let field_name = field.ident.as_ref().unwrap();
quote! { #field_name: #field_name.to_owned() }
})
diff --git a/crates/router_derive/src/macros/api_error/helpers.rs b/crates/router_derive/src/macros/api_error/helpers.rs
index b2997090785..8da29f485bc 100644
--- a/crates/router_derive/src/macros/api_error/helpers.rs
+++ b/crates/router_derive/src/macros/api_error/helpers.rs
@@ -24,13 +24,13 @@ enum EnumMeta {
}
impl Parse for EnumMeta {
- fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::error_type_enum) {
let keyword = input.parse()?;
input.parse::<Token![=]>()?;
let value = input.parse()?;
- Ok(EnumMeta::ErrorTypeEnum { keyword, value })
+ Ok(Self::ErrorTypeEnum { keyword, value })
} else {
Err(lookahead.error())
}
@@ -40,7 +40,7 @@ impl Parse for EnumMeta {
impl Spanned for EnumMeta {
fn span(&self) -> proc_macro2::Span {
match self {
- EnumMeta::ErrorTypeEnum { keyword, .. } => keyword.span(),
+ Self::ErrorTypeEnum { keyword, .. } => keyword.span(),
}
}
}
@@ -83,6 +83,13 @@ impl HasErrorTypeProperties for DeriveInput {
}
}
+ if output.error_type_enum.is_none() {
+ return Err(syn::Error::new(
+ self.span(),
+ "error(error_type_enum) attribute not found",
+ ));
+ }
+
Ok(output)
}
}
@@ -103,23 +110,23 @@ enum VariantMeta {
}
impl Parse for VariantMeta {
- fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::error_type) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
- Ok(VariantMeta::ErrorType { keyword, value })
+ Ok(Self::ErrorType { keyword, value })
} else if lookahead.peek(keyword::code) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
- Ok(VariantMeta::Code { keyword, value })
+ Ok(Self::Code { keyword, value })
} else if lookahead.peek(keyword::message) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
- Ok(VariantMeta::Message { keyword, value })
+ Ok(Self::Message { keyword, value })
} else {
Err(lookahead.error())
}
@@ -129,9 +136,9 @@ impl Parse for VariantMeta {
impl Spanned for VariantMeta {
fn span(&self) -> proc_macro2::Span {
match self {
- VariantMeta::ErrorType { keyword, .. } => keyword.span,
- VariantMeta::Code { keyword, .. } => keyword.span,
- VariantMeta::Message { keyword, .. } => keyword.span,
+ Self::ErrorType { keyword, .. } => keyword.span,
+ Self::Code { keyword, .. } => keyword.span,
+ Self::Message { keyword, .. } => keyword.span,
}
}
}
@@ -220,19 +227,21 @@ pub(super) fn check_missing_attributes(
}
/// Get all the fields not used in the error message.
-pub(super) fn get_unused_fields(fields: &Fields, message: &str) -> syn::Result<Vec<Field>> {
+pub(super) fn get_unused_fields(fields: &Fields, message: &str) -> 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(),
};
- Ok(fields
+ fields
.iter()
.filter(|&field| {
+ // Safety: Named fields are guaranteed to have an identifier.
+ #[allow(clippy::unwrap_used)]
let field_name = format!("{}", field.ident.as_ref().unwrap());
!message.contains(&field_name)
})
.cloned()
- .collect())
+ .collect()
}
diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs
index 798ee1525d2..bee3185b444 100644
--- a/crates/router_derive/src/macros/operation.rs
+++ b/crates/router_derive/src/macros/operation.rs
@@ -83,7 +83,7 @@ enum Conversion {
}
impl From<String> for Conversion {
- fn from(s: String) -> Conversion {
+ fn from(s: String) -> Self {
match s.as_str() {
"validate_request" => Self::ValidateRequest,
"get_tracker" => Self::GetTracker,
@@ -91,6 +91,7 @@ impl From<String> for Conversion {
"update_tracker" => Self::UpdateTracker,
"post_tracker" => Self::PostUpdateTracker,
"all" => Self::All,
+ #[allow(clippy::panic)] // FIXME: Use `compile_error!()` instead
_ => panic!("Invalid conversion identifier {}", s),
}
}
@@ -118,36 +119,36 @@ impl Conversion {
fn to_function(&self, ident: Derives) -> TokenStream {
let req_type = Self::get_req_type(ident);
match self {
- Conversion::ValidateRequest => quote! {
+ Self::ValidateRequest => quote! {
fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> {
Ok(self)
}
},
- Conversion::GetTracker => quote! {
+ Self::GetTracker => quote! {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(self)
}
},
- Conversion::Domain => quote! {
+ Self::Domain => quote! {
fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type>> {
Ok(self)
}
},
- Conversion::UpdateTracker => quote! {
+ Self::UpdateTracker => quote! {
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(self)
}
},
- Conversion::PostUpdateTracker => quote! {
+ Self::PostUpdateTracker => quote! {
fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, PaymentData<F>, #req_type> + Send + Sync)> {
Ok(self)
}
},
- Conversion::All => {
- let validate_request = Conversion::ValidateRequest.to_function(ident);
- let get_tracker = Conversion::GetTracker.to_function(ident);
- let domain = Conversion::Domain.to_function(ident);
- let update_tracker = Conversion::UpdateTracker.to_function(ident);
+ Self::All => {
+ let validate_request = Self::ValidateRequest.to_function(ident);
+ let get_tracker = Self::GetTracker.to_function(ident);
+ let domain = Self::Domain.to_function(ident);
+ let update_tracker = Self::UpdateTracker.to_function(ident);
quote! {
#validate_request
@@ -162,36 +163,36 @@ impl Conversion {
fn to_ref_function(&self, ident: Derives) -> TokenStream {
let req_type = Self::get_req_type(ident);
match self {
- Conversion::ValidateRequest => quote! {
+ Self::ValidateRequest => quote! {
fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> {
Ok(*self)
}
},
- Conversion::GetTracker => quote! {
+ Self::GetTracker => quote! {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(*self)
}
},
- Conversion::Domain => quote! {
+ Self::Domain => quote! {
fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type>)> {
Ok(*self)
}
},
- Conversion::UpdateTracker => quote! {
+ Self::UpdateTracker => quote! {
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
Ok(*self)
}
},
- Conversion::PostUpdateTracker => quote! {
+ Self::PostUpdateTracker => quote! {
fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, PaymentData<F>, #req_type> + Send + Sync)> {
Ok(*self)
}
},
- Conversion::All => {
- let validate_request = Conversion::ValidateRequest.to_ref_function(ident);
- let get_tracker = Conversion::GetTracker.to_ref_function(ident);
- let domain = Conversion::Domain.to_ref_function(ident);
- let update_tracker = Conversion::UpdateTracker.to_ref_function(ident);
+ Self::All => {
+ let validate_request = Self::ValidateRequest.to_ref_function(ident);
+ let get_tracker = Self::GetTracker.to_ref_function(ident);
+ let domain = Self::Domain.to_ref_function(ident);
+ let update_tracker = Self::UpdateTracker.to_ref_function(ident);
quote! {
#validate_request
@@ -205,6 +206,7 @@ impl Conversion {
}
fn find_operation_attr(a: &[syn::Attribute]) -> syn::Attribute {
+ #[allow(clippy::expect_used)] // FIXME: Use `compile_error!()` instead
a.iter()
.find(|a| {
a.path
@@ -232,6 +234,9 @@ fn find_value(v: NestedMeta) -> Option<(String, Vec<String>)> {
_ => None,
}
}
+
+// FIXME: Propagate errors in a better manner instead of `expect()`, maybe use `compile_error!()`
+#[allow(clippy::unwrap_used, clippy::expect_used)]
fn find_properties(attr: &syn::Attribute) -> Option<HashMap<String, Vec<String>>> {
let meta = attr.parse_meta();
match meta {
@@ -251,6 +256,8 @@ fn find_properties(attr: &syn::Attribute) -> Option<HashMap<String, Vec<String>>
}
}
+// FIXME: Propagate errors in a better manner instead of `expect()`, maybe use `compile_error!()`
+#[allow(clippy::expect_used)]
pub fn operation_derive_inner(token: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(token as DeriveInput);
let struct_name = &input.ident;
diff --git a/crates/router_env/src/env.rs b/crates/router_env/src/env.rs
index 518a1cac0cf..701953f6b29 100644
--- a/crates/router_env/src/env.rs
+++ b/crates/router_env/src/env.rs
@@ -63,7 +63,7 @@ pub fn workspace_path() -> PathBuf {
// for (key, value) in std::env::vars() {
// println!("{key} : {value}");
// }
- if let Result::Ok(manifest_dir) = std::env::var(CARGO_MANIFEST_DIR) {
+ if let Ok(manifest_dir) = std::env::var(CARGO_MANIFEST_DIR) {
let mut path = PathBuf::from(manifest_dir);
path.pop();
path.pop();
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index 6c6ce4893b7..4febff06f25 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -1,17 +1,5 @@
#![forbid(unsafe_code)]
-#![warn(
- missing_docs,
- rust_2018_idioms,
- missing_debug_implementations,
- clippy::expect_used,
- clippy::missing_panics_doc,
- clippy::panic,
- clippy::panic_in_result_fn,
- clippy::panicking_unwrap,
- clippy::unreachable,
- clippy::unwrap_in_result,
- clippy::unwrap_used
-)]
+#![warn(missing_docs, missing_debug_implementations)]
//!
//! Environment of payment router: logger, basic config, its environment awareness.
diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs
index cc66fccfe4a..17f4dea6ed1 100644
--- a/crates/router_env/src/logger/formatter.rs
+++ b/crates/router_env/src/logger/formatter.rs
@@ -102,9 +102,9 @@ pub enum RecordType {
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
- RecordType::EnterSpan => "START",
- RecordType::ExitSpan => "END",
- RecordType::Event => "EVENT",
+ Self::EnterSpan => "START",
+ Self::ExitSpan => "END",
+ Self::Event => "EVENT",
};
write!(f, "{}", repr)
}
diff --git a/crates/router_env/tests/logger.rs b/crates/router_env/tests/logger.rs
index 5e134a81942..824f9e825ba 100644
--- a/crates/router_env/tests/logger.rs
+++ b/crates/router_env/tests/logger.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::unwrap_used)]
+
use router_env as env;
mod test_module;
use env::TelemetryGuard;
diff --git a/crates/storage_models/src/lib.rs b/crates/storage_models/src/lib.rs
index 98d4a68c49e..7ff7845843d 100644
--- a/crates/storage_models/src/lib.rs
+++ b/crates/storage_models/src/lib.rs
@@ -63,7 +63,7 @@ pub(crate) mod diesel_impl {
type Row = Vec<Option<T>>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
- Ok(DieselArray(row))
+ Ok(Self(row))
}
}
@@ -84,7 +84,7 @@ pub(crate) mod diesel_impl {
type Row = Option<Vec<Option<T>>>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
- Ok(OptionalDieselArray(row))
+ Ok(Self(row))
}
}
}
diff --git a/crates/storage_models/src/payment_intent.rs b/crates/storage_models/src/payment_intent.rs
index 3077c884f86..7906cbc6ce4 100644
--- a/crates/storage_models/src/payment_intent.rs
+++ b/crates/storage_models/src/payment_intent.rs
@@ -236,7 +236,7 @@ fn make_client_secret_null_if_success(
status: Option<storage_enums::IntentStatus>,
) -> Option<Option<String>> {
if status == Some(storage_enums::IntentStatus::Succeeded) {
- Option::<Option<String>>::Some(None)
+ Some(None)
} else {
None
}
diff --git a/crates/storage_models/src/query/connector_response.rs b/crates/storage_models/src/query/connector_response.rs
index 49d66a2ed86..8dd4f065477 100644
--- a/crates/storage_models/src/query/connector_response.rs
+++ b/crates/storage_models/src/query/connector_response.rs
@@ -47,7 +47,7 @@ impl ConnectorResponse {
payment_id: &str,
merchant_id: &str,
attempt_id: &str,
- ) -> StorageResult<ConnectorResponse> {
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()).and(
diff --git a/crates/storage_models/src/query/process_tracker.rs b/crates/storage_models/src/query/process_tracker.rs
index 8a0ecd1beba..be7891aa425 100644
--- a/crates/storage_models/src/query/process_tracker.rs
+++ b/crates/storage_models/src/query/process_tracker.rs
@@ -88,7 +88,7 @@ impl ProcessTracker {
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
runner: &str,
- limit: u64,
+ limit: usize,
) -> StorageResult<Vec<Self>> {
let mut x: Vec<Self> = generics::generic_filter::<<Self as HasTable>::Table, _, _>(
conn,
@@ -100,7 +100,7 @@ impl ProcessTracker {
)
.await?;
x.sort_by(|a, b| a.schedule_time.cmp(&b.schedule_time));
- x.truncate(limit as usize);
+ x.truncate(limit);
Ok(x)
}
diff --git a/crates/storage_models/src/query/temp_card.rs b/crates/storage_models/src/query/temp_card.rs
index 1ed94934c1d..eb9fdc27329 100644
--- a/crates/storage_models/src/query/temp_card.rs
+++ b/crates/storage_models/src/query/temp_card.rs
@@ -25,7 +25,7 @@ impl TempCard {
pub async fn find_by_transaction_id(
conn: &PgPooledConn,
transaction_id: &str,
- ) -> StorageResult<Option<TempCard>> {
+ ) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::txn_id.eq(transaction_id.to_owned()),
|
chore
|
add lints in workspace cargo config (#223)
|
7b74cab385db68e510d2d513083a725a4f945ae3
|
2023-05-23 14:38:15
|
Shankar Singh C
|
refactor(core): generate response hash key if not specified in create merchant account request (#1232)
| false
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 74e45036ff9..5cb409a6dae 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1,5 +1,5 @@
use api_models::admin::PrimaryBusinessDetails;
-use common_utils::ext_traits::ValueExt;
+use common_utils::{crypto::generate_cryptographically_secure_random_string, ext_traits::ValueExt};
use error_stack::{report, FutureExt, ResultExt};
use masking::Secret;
use storage_models::{enums, merchant_account};
@@ -100,6 +100,12 @@ pub async fn create_merchant_account(
.attach_printable("Invalid routing algorithm given")?;
}
+ let enable_payment_response_hash = req.enable_payment_response_hash.or(Some(true));
+
+ let payment_response_hash_key = req
+ .payment_response_hash_key
+ .or(Some(generate_cryptographically_secure_random_string(32)));
+
let merchant_account = storage::MerchantAccountNew {
merchant_id: req.merchant_id,
merchant_name: req.merchant_name,
@@ -114,8 +120,8 @@ pub async fn create_merchant_account(
req.parent_merchant_id,
)
.await?,
- enable_payment_response_hash: req.enable_payment_response_hash,
- payment_response_hash_key: req.payment_response_hash_key,
+ enable_payment_response_hash,
+ payment_response_hash_key,
redirect_to_merchant_with_http_post: req.redirect_to_merchant_with_http_post,
publishable_key,
locker_id: req.locker_id,
|
refactor
|
generate response hash key if not specified in create merchant account request (#1232)
|
99ff82ef6d42899d6cb16f05c7a0c2bc193074a3
|
2023-09-01 20:07:05
|
Prasunna Soppa
|
feat(connector): [Paypal] Add manual capture for paypal wallet (#2072)
| false
|
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index e8b4269d389..adf6e51deec 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -437,8 +437,13 @@ impl
req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
+ let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?;
+ let complete_authorize_url = match paypal_meta.psync_flow {
+ transformers::PaypalPaymentIntent::Authorize => "authorize".to_string(),
+ transformers::PaypalPaymentIntent::Capture => "capture".to_string(),
+ };
Ok(format!(
- "{}v2/checkout/orders/{}/capture",
+ "{}v2/checkout/orders/{}/{complete_authorize_url}",
self.base_url(connectors),
req.request
.connector_transaction_id
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 0de25af53e2..3e4cb2a7d55 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -207,9 +207,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaypalPaymentsRequest {
let intent = if item.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
- Err(errors::ConnectorError::NotImplemented(
- "Manual capture method for Paypal wallet".to_string(),
- ))?
+ PaypalPaymentIntent::Authorize
};
let amount = OrderAmount {
currency_code: item.request.currency,
@@ -476,7 +474,7 @@ impl<F, T>
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let id = get_id_based_on_intent(&item.response.intent, purchase_units)?;
- let (connector_meta, capture_id) = match item.response.intent.clone() {
+ let (connector_meta, order_id) = match item.response.intent.clone() {
PaypalPaymentIntent::Capture => (
serde_json::json!(PaypalMeta {
authorize_id: None,
@@ -509,6 +507,7 @@ impl<F, T>
) {
(Some(authorizations), None) => authorizations.first(),
(None, Some(captures)) => captures.first(),
+ (Some(_), Some(captures)) => captures.first(),
_ => None,
}
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -517,7 +516,7 @@ impl<F, T>
Ok(Self {
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: capture_id,
+ resource_id: order_id,
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(connector_meta),
|
feat
|
[Paypal] Add manual capture for paypal wallet (#2072)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.